Navigation:    Home arrow Random Image from Folder
PHP print random image from a folder PDF  
Digg Reddit Ma.gnolia Stumble Upon Facebook Twitter Google Yahoo! MyWeb Furl" BlinkList Technorati Mixx Bookmark

This is a tutorial that will show you how to create the simplest banner rotate system. The images are stored in a folder and are randomly displayed.

The source code is posted below, with comments and it is very easy to understand.

 

Note: For the images to be able do display,the folder that contains them has to have at least read and execute rights for everybody (555) and the images at least read for everybody (444).

<?
$imglist='';
//$img_folder is the variable that holds the path to the banner images. Mine
// is images/tutorials/
// see that you don't forget about the "/" at the end

$img_folder = "images/tutorials/";

mt_srand((double)microtime()*1000);

//use the directory class
$imgs = dir($img_folder);

//read all files from the directory, checks if are images and ads them to a list
// (see below how to display flash banners)

while ($file = $imgs->read()) {
if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
$imglist .= "$file ";

} closedir($imgs->handle);

//put all images into an array
$imglist = explode(" ", $imglist);
$no = sizeof($imglist)-2;

//generate a random number between 0 and the number of images
$random = mt_rand(0, $no);
$image = $imglist[$random];

//display image
echo '<img src="'.$img_folder.$image.'" border=0>';
?>

If you want to display flash banners, then you have to change the code a bit:

The line that checks the right extension of files becomes:

if (eregi("swf", $file))

And the display image code:

echo '<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"
width="468" height="60">
<param name="movie" value="'.$img_folder.$image.'">view/30/51/
<param name="quality" value="high">
<embed src="'.$img_folder.$image.'" quality="high"
pluginspage="http://www.macromedia.com/go/getflashplayer"
type="application/x-shockwave-flash" width="468"
height="60"></embed></object>';

View demo here

If you found this tutorial useful you might be interested to read
the following:

Installing Apache, PHP, MySQL on a Windows 98/2000/XP Computer
PHP Form image verification
PHP Create Image Thumbnail
PHP Form Image Upload
Count Words in a string using PHP