BeWebmaster

Simplest PHP Image Gallery

Ad

Programmabilities.com

Suppose you want to create a gallery that displays in a Web page all the images in a specified directory. You can use the opendir and readdir functions to do this. Below is a script that creates an image gallery.
<html><head><title>Image Gallery</title></head><body>   
< ?php

//8
      $dir = "../images/";
//9      
      $dh = opendir( $dir );
//10
      while( $filename = readdir( $dh ) ) {
//12
           $filepath = $dir.$filename;
//13           
           if( is_file( $filepath ) and ereg( ".jpg$", $filename ) ) {
                $gallery[] = $filepath;
           }
      }
//16
      sort( $gallery ); 
//17
      foreach( $gallery as $image ) {
           echo "<hr/>";
           echo "<img src='$image'><br/>";
      }
?>
</body></html>

Notice the line numbers at the end of some of the lines in the script. The following discussion of the script and how it works refers to the line numbers in the script listing:

Line 8: This line stores the name of the directory in $dir for use later in the program. Notice that the / is included at the end of the directory name. Don't use , even in Windows.

Line 9: This line opens the directory with the opendir() function.

Line 10: This line starts a while loop that reads in each file name in the directory with the readdir() function.

Line 12: This line creates the variable $filepath, which is the complete path to the file.

Line 13: This line checks to see whether the file is a graphics file by looking for the .jpg extension with the ereg() function. If the file has a .jpg extension, the complete file path is added to an array called $gallery.

Line 16: This line sorts the array with the sort function so the images are displayed in alphabetical order.

Line 17: This line starts the foreach loop that displays the images in the Web page.

A working example of this PHP image gallery script can be found here: http://programmabilities.com/images/.