Optimal Telelicious Coding From AK To CT
 
« Two Geeks, One Company: Adventex Design
sfThumbnailCachePlugin - Cache thumbnails? »
 

Randomly Select Photos From a Folder with PHP

Joe Adu asked me how he could put photos in a folder and have php randomly choose one of the photos and display them. Then if more photos are added to the folder they would automatically enter in to the rotation.

Step 1: Looping through a directory with php:

  $dir = '/absolute/path/to/folder/on/server';
  $files = array();
 
  if(is_dir($dir)) {
 
    if ($handle = opendir($dir)) {
 
        while (false !== ($file = readdir($handle))) {
            $files[] = $file;
        }
 
        closedir($handle);
    }
    else{
      echo "Could not open dir: $dir \n";
      exit;
    }
  }
  else{
    echo "'$dir' is not a valid directory\n";
    exit;
  }

This fills the array called “$files” with all of the files in the directory.

Step 2: Randomly select a file

    $randomFile = $files[rand(0,count($files) - 1)];

This selects a photo at random in one line

Tags: