I would like to use a <?php include ...
command to choose one random php file from one folder.
So this is the basic idea:
<?php include 'random file: 1.php, 2.php, 3.php or 4.php';?>
I have already read articles like this or this, but they don't answer my question clearly. What is the easiest way to do that?
CodePudding user response:
// Directory to use
$directory = '.';
// Filter out directories, we only want files.
$files = array_filter(scandir($directory), fn($f) => is_file($f));
// Pick a random file
$randFile = $directory . '/' . $files[array_rand($files)];
// Include it
include $randFile;
CodePudding user response:
to include random files from another directory
$path = __DIR__."/folder";
foreach(new DirectoryIterator($path) as $file){
if($file->isFile()){
$arr[] = $file->getFilename();
}
}
$randFile = $path."/".$arr[array_rand($arr)];
include $randFile;