Zend - The PHP Company




Files and Directories

Add Code


Random File  

Type: code fragment
Added by: robf
Entered: 17/03/2000
Last modified: 08/12/1999
Rating: - (fewer than 3 votes)
Views: 7282
Picks a file at random from the given directory. Accepts wildcards.


<?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;

}  
?>


Usage Example


See the example


Rate This Script





Search



This Category All Categories