Random file selection in PHP

I would like to use the 'include' keyword in php to randomly select a file from a folder and output the content. How can I do it?

Thanks.

+2


a source to share


3 answers


Assuming you know the folder where the files are located and that the files are PHP files:



$phpFiles = glob('/path/to/files/*.php');

if (empty($phpFiles) === false)
{
    $randomFile = $phpFiles[array_rand($phpFiles)];
    include($randomFile);
}

      

+5


a source


glob()

will read the filenames in the array.
and then you can shuffle that array and pick a random element.



+1


a source


use glob to get an array of files. shuffle the array. array_shift is the first file with an array. Turn it on.

+1


a source







All Articles