I am using a PHP script to select a limited number (15) of random files from a directory, then display them on a page. The main problem is it seems to randomly midfire. Every few times I load the page, it displays more files than intended. Not a fatal error, but problematic.
Also, I haven’t figured out a way to get it to not repeat the same files. Relying on the fact that I will eventually have hundreds of files to choose from…
Any ideas? I am not really a coder…
Here is my script:
<?php
$folder = ($_SERVER['DOCUMENT_ROOT'] . "/rotators/index/");
$exts = 'php';
$files = array(); $i = -1;
if ('' == $folder) $folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) {
if (preg_match('/.'.$ext.'$/i', $file, $test)) {
$files[] = $file;
++$i;
}
}
}
shuffle($files);
$random_keys=array_rand($files,15);
require $files[$random_keys[0]];
require $files[$random_keys[1]];
require $files[$random_keys[2]];
require $files[$random_keys[3]];
require $files[$random_keys[4]];
require $files[$random_keys[5]];
require $files[$random_keys[6]];
require $files[$random_keys[7]];
require $files[$random_keys[8]];
require $files[$random_keys[9]];
require $files[$random_keys[10]];
require $files[$random_keys[11]];
require $files[$random_keys[12]];
require $files[$random_keys[13]];
require $files[$random_keys[14]];
?>
2
Answers
I have updated the logic and also added some conditions so that code can be debugged easily.
One more thing, you have fixed the limit to 15, what if there are less then 15 files? If you are sure there would be at least 15 files inside the folder then keep this.
Now, this code will load 15 different files each time when a user will refresh the page.
use shuffle() to randomise the order
use array_slice() to pick the first 15 files
add error check to ensure there are enough files to display