How to Write an image gallery in PHP

How to Write an image gallery in PHP

The code consists of a simple class with two main functions: GetAllFiles() and DisplayImages(). GetAllFiles() retrieves all the images within a specified directory and DisplayImages randomly displays them.

//set your directory here and remember to include the trailing slash
//the script will automatically pull images out of the specified directory and display them
define(”IMAGE_DIRECTORY”, “images/”);

class rotate_class {

var $Imagelist = array(); //this stores all of the images that were found in your directory
var $ImageExtList = array(); //this will store the image extensions

function GetAllFiles() {

// Open a known directory, and proceed to read its contents
if (is_dir(IMAGE_DIRECTORY)) {
if ($dh = opendir(IMAGE_DIRECTORY)) {
while (($file = readdir($dh)) !== false) {
//check to see if it is a file
if (filetype(IMAGE_DIRECTORY.$file) == “file”) {
//get the files extension and make sure it is one of our supported image types
$current_ext = substr($file,strlen($file)-3,strlen($file));
if ($current_ext == “jpg” || $current_ext == “gif” || $current_ext == “png” || $current_ext == “jpeg”) {
//push the filename and extension onto our arrays
array_push($this->Imagelist,IMAGE_DIRECTORY.$file);
array_push($this->ImageExtList,$current_ext);
}
}
}
closedir($dh);
}
}
}

function DisplayImage() {

//get the total number of images
$imagecount = count($this->Imagelist);
//randomly generate the next image that we will display
$nextimage = rand(0,$imagecount-1);

//determine the image type and return the proper header information
switch($this->ImageExtList) {
case ‘png’:
header(”Content-type: image/png”);
break;
case ‘gif’:
header(”Content-type: image/gif”);
break;
case ‘jpg’:
header(”Content-type: image/jpeg”);
break;
}

//read image into string and output it
$contents = file_get_contents($this->Imagelist[$nextimage]);
echo $contents;
}

} //end class

//create a new instance of the rotate_class class
$imagerotator = new rotate_class;

//display random image
$imagerotator->GetAllFiles();
$imagerotator->DisplayImage();
//$test = array();

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.