Creating Your Own Image Gallery With Php - A Guideline, Not A Complete Script

free web hosting
Free Web Hosting > Computers & Tech > How-To's and Tutorials > Programming > PHP

Creating Your Own Image Gallery With Php - A Guideline, Not A Complete Script

vujsa
Recently a member asked how to create a photo gallery using his various directories filled with image files. Here is an overview of the steps and fuctions needed to do this.

Assuming that the following directories exists and are full of image files:
www.testsite.web/photos/gallery1/
www.testsite.web/photos/gallery2/
www.testsite.web/pictures/album1/

In order to get the contents for a specific gallery you'll need to let the script know which one to look in. You'll need to use a link that carries the arguments needed to locate the right photos.

www.testsite.web/MyGallery/index.php?dir=photos&album=gallery1
- or -
www.testsite.web/MyGallery/index.php?dir=pictures&album=album1

Then in your script which in this case is called index.php you need to retrieve that information.

CODE

<?php
$directory = $_GET['dir'];
$album = $_GET['album'];
?>


That tells the script to get the values for the variables from the arguments passed in the link.




Now that the script knows where to find the files, we need to tell it how to read each file.

CODE
<?php
$base_url = "www.testsite.web";
$base_path = "";  // This would be "/images" if the location of the galleries was www.testsite.web/images/photos/gallery1/

$directory_name = $basepath .  "/" . $directory .  "/" . $album .  "/";  // This just sets directory to read like this: "/photos/gallery1/"

$dir = opendir($directory_name); // Open the specified directory to be read.

while ($file_name = readdir($dir)) {  // Read each file individually and perform the following instructions for each.

$html_block .="<img src="http://". $base_url . "/" . $directory_name . "/" . $file_name . ""><br>" . $file_name . "<br><br>n";
}
closedir($dir);  // Simply ends the use of that directory.
?>
...YOUR HTML HERE!
<body>
<?php echo $html_block; ?>
</body>
YOUR HTML HERE ...


This would produce a most undisired effect where all of the images in the directory will be shown in full resolution with the name of the image file below it. It would take a long time to load a page with so many large images and it would be difficult to view.
The "echo" function will simplay output everything in the variable named $html_block. This is how you would insert the HTML generated by PHP into the otherwise static webpage.


The best option for rersolving this problem is to use PHP to create thumbnail images to be displayed in a table with a link to the full size image.




In order to display thumbnails for the images in your galleries, you'll need to use the image functionfs availible in PHP in the GD2 library. This is like a really basic image editor like photoshop but you have to program each step instead of using your mouse to click on options.

Something you need to think about is that every time you modify an image on the server with PHP it is like editing an image on your computer with photoshop. Memory and cpu usage is very high. So trying to generate thumbnails on the fly would actually require much more time to load your gallery since the server needs to read each image, run the required processes on the image, generate the thumbnail, and display the image on the page. I can guarantee that if you get much traffic to you gallery and you generate your thumbnails on the fly, you'll lose hoyour hosting account on most servers.

I suggest creating a directory to hold all of your thumbnail files. This can either be a subdirectory of the gallery being used or a master directory of all of the gallery thumbnails. I like the master directory option so I'll explain that one.

You'll open the image file, resize the image and save the image in the thumbnail directory. For this example, we'll only use JPEG files. The steps to include other image file types can be discussed later.

Here is the basic run down on how to create and save a thumbnail from the original JPEG image.

Based on example given in The PHP Manual
CODE

<?php
// File and new size
$thumb_dir = "/thumbs/";
$filename = 'test.jpg';
$thumb_height = 150;

// Content type
header('(anti-spam-(anti-spam-content-type:)) image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$ratio = ($height/$width);
$newheight = $thumb_height;
$newwidth = ($thumb_height/$ratio);

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output
imagejpg($thumb, $thumb_dir, 100);
?>


This would read an image file in this case test.jpg and save a thumbnail image at the url of www.testsite.web/thumbs/test.jpg.
If the image was 800 X 600 originally, the thumbnail would be 150 X 112. If the image was 600 X 800 instead, the thumbnail would be 150 X 200.

You would then need to check and see if the thumbnail exists when you read the file in the directory. If it already exists, then display that thumbnail with a link to the full image. If the thumbnail does not exist, then create the thumbnail and display it with a link to the full image.
This is helpful if you already have a large number of images in the directory and you don't want to manually create the thumbnails one at a time in photoshop or whatevery your graphics editor software is. Also, if you do a check for the thumbnail when you read the filenames, you can add photos to the directory and the thumbnail will automatically be generated. Your gallery wuld be maintenence free as a result.




To check for the thumbnail and either use or generate the thumbnail, this is what you would need to do.

From the block of code above we modify the section that reads the filenames in the directory.
CODE

//.....NOTE THAT THIS IS JUST A PORTION OF THE CODE THAT NEEDS TO BE MODIFIED FROM THE EXAMPLE ABOVE.....

$thumb_dir = "/thumbs/";
while ($file_name = readdir($dir)) {  // Read each file individually and perform the following instructions for each.
    $filename = $thumb_dir.$file_name;
    if (file_exists($filename)) {
        $html_block .="<a href="http://". $base_url . "/" . $directory_name . "/" . $file_name . ""><img src="http://". $thumb_dir . $file_name . ""><br>" . $file_name . "</a><br><br>n";
        }
    else {
        //.....INSERT THE REQUIRED THUMBNAIL GENERATION CODE FROM ABOVE HERE!.....
    }
}


Keep in mind that you'll need to modify each piece of the code to work with the other pieces. For the most part, the script is completely written here but because I think everyone should learn to do things with instruction and examples, I won't be putting it all together. If you learn how to use each of the functions shown above and try to follow the flow of logic used to write each piece of the script, I think nearly anyone can write a code to create a photo gallery out of their existing image directorie.




PHP Functions Used In This Tutorial:PHP Statements Used In This Tutorial:PHP Super Globals Used In This Tutorial:


Here is how the finished script should flow.
  1. Open the PHP Code (<?php)
  2. Get directory information from the variables provided in the link.
  3. Open the directory that contains the images to be displayed.
  4. Read the filenames of the files in the directory.
    • For each filename in the directory do the following:
      • Check and see if a thumbnail with the same name as the file being read exists.
        • If the thumbnail exists, use the saved thumbnail.
        • If the thumbnail does not exist, create the thumbnail, save it in the correct directory, and use the thumbnail.
      • Create a variable to hold the output of this script usin g the following information:
        • Using the image thumbnail that is associated with the filename being read, display a linked thumbnail to the fullsized image. This can be displayed in a table or a simple list.
  5. Close the file directory being used.
  6. Close The PHP Code (?>)
  7. Open/Start the HTML part of the script.
    • Basically, create the entire webpage with all of the information except the part that is generated above.
  8. Insert the PHP generated HTML where required in your webpage.
  9. Close/Finish the HTML portion of the script.
  10. Save the script and request it with the following url:
    • www.testsite.web/MyGallery/index.php?dir=photos&album=gallery1
I know that this may be a little difficult to get through at first but I think that if you can learn how to use the PHP described above, you'll be able to write other scripts by yourself in the future.

Hope this is useful. cool.gif

vujsa

 

 

 


Reply

optiplex
nice job writing it , verry usefull thanks !

Reply

ryanlund2323
quite well thought out script youve got there......im currently making an image gallery script with ajax to make it all look fancy so as soon as i get it done i will post it up
Ryan

Reply

Necron
wow a great php tutorial, with all the info needed, 10x dude will try rigth away as I need a gallery smile.gif Great coding techniques used and great work, I didn;t even know that I could do this myself

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Similar Topics

Keywords : creating image gallery php guideline script

  1. A Simple Register Script - This Is a Very Simple Register-Script (3)
    Some time ago, i made a login-script. But how do you use a login-script, if you can't register.
    So this morning, I decided to make a register-script.. What you should already know: The php
    basics and a little more. How to use php and mysql together. The HTML basics (to make the forms).
    The first thing we should do, is creating the database tables. Here is the code: CODE CREATE
    TABLE `user` (   `id` int(4) unsigned NOT NULL auto_increment,
      `username` varchar(32) NOT NULL,   `password` varchar(32)...
  2. PHP Tutorial: Form Verification And Simple Validation - A One Page script for PHP form verification. (12)
    Having used various means of verifying HTML forms I believe that this method of verifying a form
    to be the best mostly because it does everything on one page. It presents the form on one page and
    then when the submit button is pressed, if all the required fields are not filled out then it will
    present the form again with all the fields intact and in red lettering will point out the fields
    that are required to be filled out in red. It is not possible to click submit using this method even
    if the user has turned JavaScript off. While it is possible to use javascript to ...
  3. Creating A Php Login Script - A thorough look at the process behind it (3)
  4. Very Simple Login-script - This is a very simple and secure login-script (18)
    Hi. This is my first post here. please Tell me if i do something wrong. This is a very simple and
    secure login script. I will try to add as many comments as possible, to make it easier to
    understand. Lets start with the database. Just make a new SQL file, and call it whatever you want.
    Paste this code: CODE CREATE TABLE `user` (   `id` int(4) unsigned
    NOT NULL auto_increment,   `username` varchar(32) NOT NULL,   `password`
    varchar(32) NOT NULL,   `level` int(4) default '1',   PRIM...
  5. Attack Script In Php - This is a funny attack script that i made (5)
    Hey! I am going to share an attack script that i made for some time ago. I made it, as a test
    for my game.. And ofc, you can use it for your game to. It is still version 1.0. But I want you to
    learn something from it /wink.gif" style="vertical-align:middle" emoid=";)" border="0"
    alt="wink.gif" /> This is my second tutorial here, and I will try to make it better than my first
    one /smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" /> Here is
    the SQL File. CODE CREATE TABLE `characterss` (   `health` int(2...
  6. PHP: Writing A Generic Login And Register Script - (13)
    Now there are basically 3 functions that a user management system provides: login, register, and
    protection. A user management system can do more than this but that is all that this tutorial will
    be covering. I will try to explain what I am doing as I go along but to fully understand what is
    happening you should have a basic knowledge of PHP, SQL, and HTML. This tutorial assumes you are
    using MySQL, adjust accordingly for a different DBMS. First off lets define the database table
    where our users will be stored. Using phpMyAdmin run this statement to create our table...
  7. Simple User Validation Script - (5)
    This tutorial will show you how to create a simple user validation script with PHP. We will need
    two files: "protect.php" and "login.php". The protect file is not meant to be viewed by itself. In
    order to protect a page, you need to include that file by using PHP code like the following: CODE
    include("protect.php"); Keep in mind that this needs to be in between your
    tags. This bit of code uses the include function. It is a handy function that reads all the
    information contained in one file and temporarily adds it to another. For example, this c...
  8. Creating A Content Managing System - Using MySQL (15)
    This tutorial is for beginners that know some php and know the basics of MySQL. I will tell you how
    to make a simple Content Managing System. A Content Managing System is a way of editing and adding
    your content using your browser, so you dont have to go trough ftp all the time. This CMS uses
    MySQL databases. So what we need to do is to create a database. Well go through this step by step to
    make it as easy as posible: 1. Go in to your cPanel and select phpMyAdmin. 2. Write the name of
    your database in the input box under the text: Create new database. This database ...
  9. Creating And Using Includes With PHP - A simple tutorial (6)
    OK so you are now wanting to learn to use PHP and a few includes which are file(s) that you place
    into your script on any given page to indlude stuff that you have written previously. I did see
    another tutorial on such matters but possibly this tutorial will make more sense. PHP has the
    abilty to include other PHP files into the current script that is being processed by the server. Let
    us just take a simple example. This will be a file that will connect yo your database and a
    specified table. It will include all the necessary parameters to actually do just that. This...
  10. PHP Tutorial: Menu Or Sidebar Script For CMS101 - and other applications as well (6)
    A Php Menu-builder Tutorial This Sidebar Menu-builder code and the php scripts are adapted from
    a Tutorial on the Astahost.com Forum titled : CMS101 - Content Management System Design .
    Since the original tutorial's author (vujsa) did such a marvellous job of describing the system
    in the original Topic posting, I will not attempt to explain it here, rather, I invite you to have a
    look at his Topic and learn from it. The Basic tutorial provided coding for developing a table-based
    web-site template which used php includes and embedded data to create a &...



Looking for creating, image, gallery, php, guideline, complete, script

Searching Video's for creating, image, gallery, php, guideline, complete, script
advertisement




Creating Your Own Image Gallery With Php - A Guideline, Not A Complete Script



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE