Mega Code Archive

 
Categories / Php / File Directory
 

Working with files - get a random file from a directory

This is great for displaying a random image, or random include()-ing a text file. <? function getRandomFile($start_dir) { /* returns the name of one random file from within a directory */ chdir($start_dir); $dir = opendir('.'); while (($myfile = readdir($dir)) !==false) { if ($myfile != '.' && $myfile != '..' && is_file($myfile) && $myfile ! = 'resource.frk') { $files[] = $myfile; } } closedir($dir); chdir('../'); srand ((float) microtime() * 10000000); $file = array_rand($files); return $files[$file]; } ?> Example 1: random image: <? $imagesDir = 'images/something'; $imageURL = getRandomFile($imagesDir); $image echo "<img src='{$imagesDir}/{$imageURL} ' alt='' />"; ?> Example 2: random include(): <? $includeDir = 'randomquotes'; $quoteFile = getRandomFile($includeDir); include("{$includeDir}/{$quoteFile}"); ?>