Sunday, April 23, 2006

PHP : Showing an image randomly from a collection of images

Following code shows one .jpg image randomly from all images in a directory. The code needs to be saved in a file in the directory containing the images. This code can be used for creating random image gallery.

<?php
############### settings #############
$path = "/image_gallery/";
#######################################
$dir = $_SERVER['DOCUMENT_ROOT'].$path;
$ig = Array();
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
                if(ereg("\.jpg$",$file))
                array_push($ig,$file);
        }
        closedir($dh);
    }
}
$num = mt_rand(0,count($ig)-1);
echo "<img src=\"".$ig[$num]."\">";
?>

Notes :
  1. The code opens a directory specified by $dir and puts all jpg filenames in an array $ig.
  2. mt_rand function returns an integer between 0 and count of $ig i.e. number of jpg images in the directory.

3 comments:

Anonymous said...

Actually mt_rand function of PHP is Pseudorandom number generator function. Pseudorandom number generators are not truly random number. You can get detail of Pseudorandom random generator on
http://en.wikipedia.org/wiki/Pseudorandom_number_generator

Shrinivas

Ketan said...

Thanks for the link ! That article is very informative. You had this algorithm study in your curriculum ? It seems you took your studies quite seriously :-)

Anonymous said...

No man that algorithm is not part of my study but during my work in B'lore I found this thing.