<?php function rand_file($dir, $pattern = "-no-pattern-") {
/* returns the name and path of a random file. If $base is a directory, * and $pattern is not supplied any file inside it $base can be chosen.
* $pattern accepts regular expressions, so you can match all files
* beginning with the letter "n" by calling with directory/n+
* slightly revised version removes the world's worst nested ifs
*/
$direc = (is_dir($dir)) ? $direc = $dir : $direc = dirname($dir);
if (isset($direc)):
$dh = opendir($direc);
else:
return false;
endif;
while ($file = readdir($dh)) {
/* get a list of files in the directory. We're only looking at files
* so we can't return a link or a directory
*/
if (is_file("${direc}/${file}") && (ereg("$pattern", "$file") ||
$pattern == "-no-pattern-"))
$file_list[] = $file;
}
closedir($dh);
srand((double)microtime() * 100000);
/* pick something from the file list at random */
return (sizeof($file_list) > 0) ? $file_list[rand(0, (sizeof($file_list)
-1))] : false;
} ?>
|
|