Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Selects and passes along a random image from a directory.
<?
/*
Displaying A Random Image From A Directory Via PHP
Copyright 2007 Doug Vanderweide
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//set path to images directory
//this path is relative to root directory
//keep the trailing slash!
$img_path = "images/";
//set allowable image extensions regular expression
//this allows .jpg, .jpeg, .png or .gif extensions, case-insensitive
$exts = "/(.jpg)|(.jpeg)|(.gif)|(.png)$/i";
//check if images directory exists
if(is_dir($img_path)) {
//open directory
$img_handle = opendir($img_path);
//iterate through all items in directory
while (false !== ($img_file = readdir($img_handle))) {
//if item is a file (not a link / directory), add to array
//this code uses a PERL-compatable regular expression to test file extension
if (preg_match($exts, $img_file)) {
$img[] = $img_file;
}
}
//close the directory handle
closedir($img_handle);
//seed random number generator
//not needed if you are using PHP 4.2.0 or later
mt_srand();
//get upper boundary of image array
//die if no files matched regular expression
if(count($img) == 0) {
die("no images in image directory");
}
else {
$len = count($img) - 1;
}
//generate a random index number
$index = mt_rand(0, $len);
//set source for image to be random index
$img_src = $img_path . $img[$index];
//set image type depending on extension
$ct = "Content-type: image/";
//get image extension
$temp = explode(".", $img_src);
$temp = array_pop($temp);
$temp = strtolower($temp);
//complete content type
switch($temp) {
case "png":
$ct .= "png";
break;
case "gif":
$ct .= "gif";
break;
default:
$ct .= "jpeg";
}
//send header indicating this is an image
header($ct);
//output image
readfile($img_src);
}
else {
//halt page execution if image directory does not exist
die("no such directory!");
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.