0

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);
?>
jww
  • 97,681
  • 90
  • 411
  • 885
user2334436
  • 949
  • 5
  • 13
  • 34

4 Answers4

1

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.

SharpC
  • 6,974
  • 4
  • 45
  • 40
Ole Haugset
  • 3,709
  • 3
  • 23
  • 44
  • This gets file names in the directory. i need it to display the content. I'm not sure how to use the output of the array with the fopen. – user2334436 Sep 20 '14 at 09:11
  • Sorry, I didnt read your question correctly. Ive updated my response now so that it will post the content of a random file instead – Ole Haugset Sep 20 '14 at 09:28
0

use function name with parameters in while loop condition and check function returning a file name or not. Check the following link for detail http://php.net/manual/en/function.readdir.php

Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
vinod
  • 2,850
  • 1
  • 18
  • 23
0

Try this:-

Use glob function to get all files in a directory, and then take a random element from that array and return it. Then read the file and echo its content.

function get_random_file($dir = 'folder_name')
{
    $files = glob($dir . '/*.txt');
    $file = array_rand($files);
    return $files[$file];
}

   $fh = fopen($myFile, 'r');
   $theData = fread($fh, filesize($myFile));
   fclose($fh);
   echo $theData;
Garima
  • 174
  • 6
  • $myFile is not identified in $fh = fopen($myFile, 'r');. – user2334436 Sep 20 '14 at 09:12
  • Make sure that you have to give here directory path also. For example :- fopen("/home/".$myFile, "r"); Please check the fopen php manual. http://php.net/manual/en/function.fopen.php – Garima Sep 20 '14 at 11:13
0

You have wrong slash in your directory.

$dir = 'wp-content\files'

should be

$dir = 'wp-content/files'

It should be forward slash not back slash. Also check permission of the directory that you are accessing.

user4055288
  • 551
  • 5
  • 11