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
$dir = "../images/"; #8
$dh = opendir( $dir ); #9
while( $filename = readdir( $dh ) ) { #10
$filepath = $dir.$filename; #12
if( is_file( $filepath ) and ereg( "\.jpg$", $filename ) ) { #13
$gallery[] = $filepath;
}
}
sort( $gallery ); #16
foreach( $gallery as $image ) { #17
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.
Line 10: This line starts a while loop that reads in each file name in the directory.
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. 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 using 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.
Chief Programmabilities
Programmabilities.com