Search code examples
phpphp-5.4

Selecting a file from a directory randomly and then display it


I have a directory which contains several text files. What I'm trying to do is to randomly select one of the files and then display it. Here's what i got so far, but i still haven't managed to get it working. Any idea's? Thanks.

<?php
function random_pic($dir = 'wp-content\files')
{
    $files = opendir($dir . '/*.txt');
    $file = array_rand($files);
    return $files[$file];
}

while(!feof($file)) { 
        echo fgets($file) . "<br />";
    }

    fclose($file);
?>

Solution

  • scandir will put all elements in the directory into an array. Then use array_rand to choose a random element from the array.

    $dir = "/path/to/pictures/";
    $dirarray = scandir( $dir );
    unset($dirarray [0]);
    unset($dirarray [1]);
    $content = file_get_contents( $dir . $dirarray[array_rand($dirarray )] );
    echo $content;
    

    The unset commands are to remove . and .. from the array. This would for example result in echoing picturename.jpg.