user2334436 user2334436 - 1 year ago 67
PHP Question

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.

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 />";


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download