I have a question bugging my mind. I have this PHP script that lists all the images from a directory and write on the page:
<?PHP
$directory="photos";
$sortOrder="newestFirst";
$results = array();
$handler = opendir($directory);
while ($file = readdir($handler)) {
if ($file != '.' &&
$file != '..' &&
$file != "robots.txt" &&
$file != ".htaccess") {
$currentModified = filectime($directory."/".$file);
$file_names[] = $file;
$file_dates[] = $currentModified;
}
}
closedir($handler);
//Sort the date array by preferred order
if ($sortOrder == "newestFirst"){
arsort($file_dates);
} else {
asort($file_dates);
}
//Match file_names array to file_dates array
$file_names_Array = array_keys($file_dates);
foreach ($file_names_Array as $idx => $name) $name=$file_names[$name];
$file_dates = array_merge($file_dates);
$i = 0;
//Loop through dates array and then echo the list
foreach ($file_dates as $$file_dates){
$date = $file_dates;
$j = $file_names_Array[$i];
$file = $file_names[$j];
$i++;
echo "<img src=photos/$file>\n";
}
?>
How would it be possible, in a folder with 100 files to list only 20 files at a time, and at random, meaning every time I refresh the page 20 random pictures load?
How could I do it?
If you don’t need multiple pages, but only on page refresh, you can do it as simple as this:
Create list of the images from the directory and put them into an array.
Generate 20 random numbers within the size of the array.
Output only the generated images from the random keys you just obtained.
The code should be simple enough to write, so I’m not posting any examples.