Scriptplayground

 Print Page | Close Window

Random Image Loader

Display a random image via PHP

Relative path to the images, if the files are in the same directory leave it blank.

$img_folder = '';

Array of allowed image types, seperate each with a "|" character

$extensions = 'jpg|jpeg|png|gif';
$extensions = explode('|', $extensions);

Assign the file array and set the folder if needed

$files = array(); 
if($img_folder == '') 
	{
	$img_folder = './';
	}

Open the directory and start traversing through the directory, check the extension type and if it is good, increment "$x"

$handle = opendir($img_folder);
while(false !== ($file = readdir($handle))) 
	{
	foreach($extensions as $extension) 
		{
		if(preg_match("/\." . $extension . "$/x", $file)) 
			{
			$files[] = $file;
			$x++;
			}
		}
	}

We have finished searching through the directory, so lets close it

// Close the directory handle
closedir($handle);

Generate a unique seed for PHP 4.2 and earlier

if(phpversion() < "4.2")
	{
	mt_srand((double)microtime()*100000);
	}

Finally send the image url to the browser

print $img_folder . $files[mt_rand(0, $x-1)];

To display the img, just apply some "img" tags on your site and point to this php page

<img src="PATH/TO/FILE.php" alt="" />

Here is the completed code for easy copy & pasting.

// PHP Image Rotator
// simply drop this PHP into a folder of images
// and call it with a little HTML
// Usage: <img src="PATH/TO/rotator.php" alt="" title="" />

$img_folder = '';
$extensions = 'jpg|jpeg|png|gif';
$extensions = explode('|', $extensions);
$files = array(); 
if($img_folder == '') {
  $img_folder = './';
}
$handle = opendir($img_folder);
while(false !== ($file = readdir($handle))) {
  foreach($extensions as $extension) {
    if(preg_match("/\." . $extension . "$/x", $file)) {
      $files[] = $file;
      $x++;
    }
  }
}
// Close the directory handle
closedir($handle);
if(phpversion() < "4.2") {
  mt_srand((double)microtime()*100000);
}
print $img_folder . $files[mt_rand(0, $x-1)];

That is the end of the article. If you have any questions or comments, feel free to post them below..


Find this article at:
http://scriptplayground.com/tutorials/php/Random-Image-Loader/