Random Image

By Zen on Jul 28, 2008

How To Use It:
$dir="./"; - This is the path (directory) to the images, it must include the foward slash.
$nimg="10"; - Number of images in the folder.
$itype="jpg"; - The image type (don't Include the ".").
$bor="1"; - The image border, 0 is no border, 1 is a 1 pixel border.

Add the code the where ever you want it to apprear on the web page.
Make sure the web page file type is .php.
All image names must be a number (Example: 1.jpg 2.jpg 3.jpg).

<?php
$dir="./";
$nimg="10";
$itype="jpg";
$bor="1";

$rnumb=rand(1,$nimg);

echo "<img src="".$dir."".$rnumb."".$itype."" border="".$bor."">";
?>

Comments

Sign in to comment.
bone282   -  Mar 27, 2010

i added the $fileType array

function dir2array($targetDir, &$fileType){
   $filesArray = array();
   if ($handle = opendir($targetDir)){
      while (false !== ($file = readdir($handle))){
         if(in_array(end(explode(".", $file)), $fileType)){
            $filesArray[] = $file;
            }
         }
         closedir($handle);
      }
   if (count($filesArray) > 0) {
      return $filesArray;
   } else {
      return FALSE;
      }
   }

// Usage Examples:

$arrayName = dir2array("path/to/directory", $arr = array("jpg", "png", "gif")); 
$randfile = $arrayName[array_rand($arrayName)];

if(FALSE !== ($arrayName = dir2array("path/to/directory", $arr = array("jpg", "png", "gif")))){ $randfile = $arrayName[array_rand($arrayName)]; }
 Respond  
bone282   -  Mar 26, 2010

this should meet what's required
and can be quickly edited to handle a $fileType array

// Put all files of a directory of A selected filetype into an array.

function dir2array($targetDir, $fileType){
    $filesArray = array();
    if ($handle = opendir($targetDir)){
        while (false !== ($file = readdir($handle))){
            if(end(explode(".", $file)) == $fileType){
                $filesArray[] = $file;
                }
            }
            closedir($handle);
        }
    if (count($filesArray) > 0) {
        return $filesArray;
    } else {
        return FALSE;
        }
    }

// Usage examples:

$arrayName = dir2array("path/to/directory", "jpg");
$randfile = $arrayName[array_rand($arrayName)];

if(FALSE !== ($arrayName = dir2array("path/to/directory", "png"))){ $randfile = $arrayName[array_rand($arrayName)]; }
 Respond  
Jonesy44   -  Jul 28, 2008

Use a directory listing, then use the rand number to select one of the images.

 Respond  
Hawkee   -  Jul 28, 2008

Would be a bit nicer if the images didn\'t need to be named like 1.jpg, 2.jpg, etc. You could just select the Xth image in a directory regardless of the name.

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.