Domain Empire

Greatest Image Gallery Tutorial Ever

Spaceship Spaceship
Watch
Impact
4
I guess it might just be time for another tutorial from my part. So, I will enlighten you with the basics of a PHP based image gallery script. I am not going to betray a whole code to you at first, because if I do, you will not learn jack shit. I will go trough the few most important thing you need first very thoroughly, and give you little example snippets.

Ok so you want a gallery. Let´s start to think of what we actually need to do. I´ll help you. To run a succesful image script, you need to:

1. Scan a directory for images
2. Display images in thumbnails
3. Have a page on which you display an image

That was not so hard. You really don´t need much. Remember that from these basics and a bit of experimenting you can expand your script to a huge image archive with functions you´ve never even dreamt of. Now, relax and sit back, because this is going to be a long read. I´ve tried to keep it simple, but it is in my nature and desire to explain every bit of PHP code I want you to use. After all, if you don´t know what it does, how can you learn from it?
Scanning the directory

Ok this is not extremely difficult. First, you´ll need a directory in which all images are. Let´s make this directory "images/". You can also set a variable for this (for example $image_dir, which I will do. This is actually the very first line of PHP code in my example:

Code:
$path = "images";

Notice that I didn´t add a slash behind it. I will do that only whenever I need to, for example in the scanning piece of code I will give you just a bit later on in this tutorial.

Make the directory first, and upload some images in it, so we can see if the script is working already. Once you´ve done that, you can make a new file, "index.php" in the base directory of where your gallery will be.

Now, finally we´re actually going to scan the directory. I´ve set a value $path to "images", so all images will be in the "images" directory. When we´re scanning the directory, we´ll also at the same time count the number of files. This is nice because in the script we can brag about how many images we have.

Also, you´ll have to create an array. An array is kind of like a list of seperate items. Once the scanning is done, you can make a loop, so that for each item in the array (read: each image in the directory) it can perform a certain action. Check out my example snippet, I will discuss it in a minute.

Code:
$files = "0";
$handle=opendir($path);
while ($file = readdir($handle)) {
if(!is_dir($path."/".$file) && $file != "." && $file!="..") {
$extension = explode (".", $file);
$extension_i = (count($extension) - 1);
$ext = $extension[$extension_i];
if($ext=="jpg"||$ext=="jpeg"||$ext=="JPG"||$ext=="JPEG") {
$images[$files] = $file;
$files++;
}
}
}

You´ve noticed I immediately set $files to 0. This variable will increase with each file that is "approved". Then, I´ve set $handle to a function ("opendir()"). $handle is now a shorter way of writing opendir($path), and remember that I previously set $path to "images". I´ll use $handle in the next line, to conveiniently write the function opendir() in readdir(). These two functions actually make up the scanning part of a directory. Now all that is left to do is filter out the good files, because with scanning, it will also have included all the folders, and "." and "..".

That´s what the next 7 lines are for. Before we go any further with bothering to check for the file´s extension etc. we gotta find out if it even is a file at all. After all, it could just as well be a directory. To find out we use the is_dir function. This function will return a positive reply when the file is a directory, and a negative one when the file isn´t. We need a negative reply, so we´ll only proceed "if(!is_dir($path."/".$file))". Adittionally, the files can´t be the useless "." or "..".

Once $file doesn´t appear to be a directory, "." or "..", we can proceed. We now have to find out the file´s extension. The only files that we´re searching for are JPG files, not any other. DOC, PDF, EXE and nearly 99% of all other extensions aren´t images and don´t belong in an image gallery. GIF and PNG are also common file extensions, but GIF is difficult to resample, and PNG, I might cover some other time. Should you wish to include PNG too, edit the image resampling file (later on in this tutorial) and this scan snippet, so that the gallery will recognise PNG files.

The way we search for extensions is taking out the last few letters (and numbers, for that matter) that come after the last dot (.). To easily do this, we create yet another array. This is done with explode(), that will create seperate entries in an array for all the bits and pieces between certain characters. "$extension = explode (".", $file);" will create an array names $extension of all the bits and pieces in $file that are between "." characters. The next line, we count the number of values in the given array (remember, a file name can have multiple dots in it), and after that we make $ext of (what we calculated is) the last value from $extension. This method can bytheway be used in any other script that needs to scan a directory.

Ok we got the extension. Now, if the extension mathes certain extensions we´ve defined (done crudely in my example, but it´ll do) ("jpg", "jpeg" and the uppercase versions of em), we´ll do the next two things. First, we´ll add the image to the final array of images ("$images") and we´ll increase the counter. This is done simply with the "command" $files++;. This means that $files will be increased by one.

Now, neatly close the three loops and conditionals ("while ($file = readdir($handle))", "if(!is_dir($path."/".$file) && $file != "." && $file!="..")" and "if($ext=="jpg"||$ext=="jpeg"||$ext=="JPG"||$ext=="JPEG") "). This is also very important, because if you do not do this right fast, you could get extremely confuzed and things will go wrong. So much for scanning the directory bit.

Update: As Erik kindly pointed out in the comments, the files are not in any order. To have them ordered alphabetically, amend on a new line: "sort($images);". PHP´s website is an excellent resource to check out more information about the sort function.
Part One: The Gallery View
Preparing the overview

To make sure you will only get the thumbnails and overview of all images in the directory when you want to, we´ve got to make sure this doesn´t happen when you _did_ select an image. Selecting an image to view will be done with GET values. For example, $_GET["image"] for the URL "index.php?image=Kleurenblind.jpg" is "Kleurenblind.jpg". This technique is also used in a lot of fora and PHP sites. For the gallery, instead of $_GET["image"] we will use $_GET["i"] (gives eg. "index.php?i=Goatse.jpg"), which is alot shorter and more conveinient.

Anyway, to check if the visitor isn´t trying to view an image already, check if $_GET["i"] isn´t there already. Make a simple conditional.

Code:
if(!$_GET["i"]) {

Ofcourse after the snippet of code for the "overview" you will have to close the conditional, with }, or things will get really messed up.
Displaying the thumnails

Now we´re getting to the part that is actually noticable for the visitor. Here you will do a lot of customisation should you intend to use this tutorial for your own gallery script.

I will give you the script that generates the thumbnails real quick, because it is much more complicated and you won´t need to change it very much anyway.

So, now that you´ve scanned a directory, selected the files and put them all in an array, it is time we should do something with em. Because the array of files is good, we will treat each and every one of them. After all, the files´ve been evaluated before. That is why we´ll simply use the foreach code. For each value from an array it will repeat an action.

The proper syntax for it is real easy and goes like this

Code:
foreach($images as $image) {

Looks like plain english to me. Now, every time it loops trough the loop, it´ll take the appropriate value from the array and it´s named $image. I love the simplicity.

Since I won´t be taking care of any extra HTML or webdesign in this tutorial (because you should design your own sites) we move on to the making of the thumbnail right away. After all, this has to be done before you can display a thumnail at all. Here comes the code, which I will discuss only generally.

Code:
$source = $path."/".$image;
$tsource = "thumbs/".$image;
$thumbnail_h = "100";
$quality = "60";
if(file_exists($source)&&!file_exists($tsource)) {
$size = getimagesize($source);
$w = round($size[0]/($size[1]/$thumbnail_h));
$h = $thumbnail_h;
$resize = imagecreatetruecolor($w, $h);
switch ($size['mime']) {
case 'image/jpeg':
$im = imagecreatefromjpeg($source);
imagecopyresampled($resize, $im, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);
imagejpeg($resize, 'thumbs/'.$image, $quality);
break;
case 'image/png':
$im = imagecreatefrompng($source);
imagecopyresampled($resize, $im, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);
imagepng($resize, 'thumbs/'.$image, $quality);
break;
}
imagedestroy($im);
}

We start off by setting a few variables. For each time we go trough the foreach loop, we will process a different file, resulting in a different $source each time. This is defined in the first line. Remember that you set $path to somewhere in the beginning.

Next, there´s something about thumbs. WTF? I´ll tell you this. "thumbs/" is the folder that we´ll be storing thumbnails in. This directory can be changed to whatever you like. Make sure it is writeable by server (set CHMOD to 0777 or something like that). In it, we can store thumbnails that have been made already, so next time a person wants to see those thumbnails the script will not have to bother to generate it all over again. The $tsource variable I´ve made to conveiniently check if this thumnail doesn´t already exist somewhere later.

The next two variables, $thumbnail_h and $quality are very customizable and define the height of any generated thumbnail, and the quality in which it should be displayed. Change $thumbnail_h in whatever number you fancy. $quality has to be something between 1 and 100. 100 is the best quality but gives larger files etc., so will take a bit longer to load.

Now we´ve come to a conditional, "if(file_exists($source)&&!file_exists($tsource)) ". This conditional is for extra security and to save time. It first (double)checks if the file that´s about to be processed actually exists, and after that it checks wether or no a pre-generated thumnail doesn´t exist yet. If it does, this conditional is violated, and the script does not attempt to generate one. This little check saves a big load of time.

The next few lines, up to and including "imagedestroy($im);" do not need customisation real bad. I will not discuss them but I can tell you it resamples $source and saves it.

To close off the foreach loop, we write:

Code:
echo '<a href="index.php?i='.$image.'"><img src="'.$tsource.'" border="0"></a> ';
}

Because you´ve already checked for a thumnail and made sure there is one present at $tsource you will simply use it right now. There´s nothing difficult about that. Also, the link to view the image file is "index.php?i='.$image.'", so in part Two of this kickass tutorial we will make the page fordisplaying these images using the $_GET["i"] variable, remember?

Now, as an extra bonus we´ve already counted the number of files when we scanned the directory. It´s nice to tell our visitors about it. I´ll let you do this extremely easy line yourself. The value is "$files". Wow, I´m glad you did something for yourself :P.

Close off the conditional "if(!$_GET["i"])", and we´re done for part One. You can now upload index.php to your PHP enabled webserver (or localhost for that matter). Remember to make an image directory (and define it in $path), upload some nice porno, and make a directory "thumbs" (CHMOD 0777). Gently browse to your script in your browser and behold, it works!
Part Two: The Image View

Ok so now that you´ve made a nice page that displays the thumbnails and gives the links etc. it´s time to properly display the image. Ofcourse you can link directly from the index, but this has as disadvantages that visitors can easily rip off all your images and navigating between them is made more difficult.

What you also could basically do is something like

Code:
echo '<img src="'.$path.'/'.$_GET["i"].'">';

What it does is display whatever image is in the $_GET["i"] variable. This will do for the lazy people here, but it isn´t a very nice way to treat your visitors. What they´d probably much more appreciate is a link to the next and previous image in the gallery. Also, a link back to the "overview" is often appreciated, and arranged easily.

Again we start off with a conditional. To make sure we only try to display an image when the visitor is trying to view an image, is check wether or not there´s something in the $_GET["i"] variable. Additionally, it would be nice to check if the file we´re trying to view exists. As you´ve already figured out yourself, it goes like

Code:
if($_GET["i"]&&file_exists($path.'/'.$_GET["i"]))

Easy as pie. You may have noticed that you can just sum up your terms seperating them by "&&" or "AND" if you want both terms to validate, or by "||" or "OR" if you want either one of em. two of the same kinds ("&&" and "AND" for example) have different priorities over eachother, but for now don´t worry about this.

Let´s get right on to displaying the picture now, we can do the navigation part after that. I gave you a snippet of example code for that a bit earlier on, which is real easy to think of. However, you can also use a function to look up information about the image, for example the width, height, filesize, last modified, last accessed, etc. For detailed information about these functions check out PHP´s official website, and look for some in the "filesystem" functions. Note: in the piece of code that resamples the images to thumnails also one of these functions is used, getimagesize(). It looks up the original dimensions and with a formula it calculates the new dimensions.

Think of some nice way to display your picture.

We now move on to the navigation part. This requires some logical thinking, though it isn´t difficult. What I thought was the easiest way out is regenerate the array of files in the folder, find which number the current file has in the array, and from that substract one (and also add one up), look up which file goes with those two numbers, and generate the link from that. So, we´ve got to scan the directory again. However, we do not need to copy the scan code again. This is, because we´ve put it outside the overview/image view conditionals, and it is executed in either case.

Let´s find out which key (as it´s called) our current picture has. You can search an array for a value and have the key returned by using the array_search(). The array returned from the scan is named $images, and in $images we´re searching for $_GET["i"]. So, the syntax for the function is "array_search($_GET["i"],$images)". We want the key found to be stored in a variable, so

Code:
$id = array_search($_GET["i"],$images);
$files2 = $files-1;

I defined $files2 seperately, because counting the total number of files starts with 1 (like 1, 2, 3, 4, 5... in $files), but the counting in arrays starts with 0 (eg $images["0"], $images["1"], etc.).

Now we´re going to make the script figure out what to do next. It is really simple. If the current $id is between "0" (the first) and $files2 (the last), the visitor is able to navigate both back and forth. Therefore simply calculate the next and previous ID (wooo, difficult) and link to that with looking up the proper filename in $images.

Next conditional will activate when $id is "0", so when we´re browsing the first file, and can´t go to the previous image anymore. The last conditional is ofcourse in case we´re trying to view the last image.

Code:
if($id>"0"&&$id<$files2) {
$next_id = $id+1;
$prev_id = $id-1;
echo '<a href="?i='.$images[$prev_id].'">prev</a>, <a href="?i='.$images[$next_id].'">nxt</a>';
}
if($id=="0") {
$next_id = "1";
echo 'prev, <a href="?i='.$images[$next_id].'">nxt</a>';
}
if($id==$files2) {
$prev_id = $files2-1;
echo '<a href="?i='.$images[$prev_id].'">prv</a>, nxt';
}

Appendix
In case you´re still reading this, this tutorial is now finished. I hope this tutorial is clear enough for you. While writing the tutorial, I also wrote the gallery script itself. I´ve written galery scripts before so that went pretty okay, though I did make (and correct) a few mistakes. Previously, I intended to paste exactly the same bit of code in both the overview and image view part. This is ofcourse unnessecary, because if I´d paste it outside and above both conditionals it would still be executed either way. So, I corrected it, but I don´t know if my long story still makes a lot of sense. Anyway, I appreciate any kind of negative or positive feedback, but I love constructive feedback, aight? You can use the comments function of this blog for that, I´m sure.

The tutorials script as I´ve got it right now is viewable at http://minnwyb.beigetow[....]dex.php. notice that I still didn´t do anything about the design. The design of your gallery is yours to do, and since I have no need for one I don´t do mine. Also, by you having to dig trough the code yourself to design whatever there is to design, you _will_ understand the code better if you didn´t already. It is not hard.


Enjoy
The source of my script is free to download (please leave the notice where it is) here .

Ofcourse a little namebucks donated if you really like this tutorial would be much appreciated, but I barely dare ask for it :P Do as you like. The tutorial took me 2 days to write. Have fun, and for questions, post them up in this thread or contact me on msn (my msn is <np username> @hotmail.com
 
1
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
0
•••
great tutorial, wish more people had seen this.
 
0
•••
Great tutorial, very detailed and well explained. Very helpful to the webmasters and to the novice... Keep it up!




______________________________________
Brochures Printing Services
"Attempt the impossible in order to improve your work."
 
0
•••
ace tutorial, a gallery script is is my next thing to learn, so this is great!

thanks
 
0
•••
I'm glad it's of use. I've also got a tutorial on writing a shoutbox and one on writing an upload form.
 
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back