Displaying a random image in your page is cool & fun. It's also useful if you want to display random banners or such. Here it is:
Listing 1: random_img.php
<?php
/**
* random_img.php :
* This script selects a random image from a specified
* directory and outputs the image to browser.
*/
/* output selected image to browser */
function out2browser($filename)
{
switch($type) {
case IMAGETYPE_PNG:
$img = imagecreatefrompng($filename);
header("Content-type: image/png"); imagepng($img);
break;
case IMAGETYPE_GIF:
$img = imagecreatefromgif($filename);
header("Content-type: image/gif"); imagegif($img);
break;
case IMAGETYPE_JPEG:
$img = imagecreatefromjpeg($filename);
header("Content-type: image/jpeg"); imagejpeg($img);
break;
}
}
/* change to your images directory */
$imgpath = "C:/www/img/avatar";
/* list images */
$files = scandir($imgpath);
foreach($files as $file) {
/* select only gif, jpg and png images */
if ($ext == '.gif' || $ext == '.jpg' || $ext == '.png') {
$images[] = $file;
}
}
/* select random image */
$img = $images[$val];
out2browser("$imgpath/$img");
?>
The script above will display a random image from the specified directory. Use the script above in your <img> tag like this:
<img src="random_img.php" border="0" alt="my random image" />
Related Article
Hillbilly Geek on Dec 27, 2008:
$ext = strtolower(substr($file, -4));
then it will handle both upper and lowercase filenames
Otherwise, this is one of the few scripts that gave me no problems, and seems to work well