What are some methods in PHP to display a random selection of images from a folder with varying file names?
To display a random selection of images from a folder with varying file names in PHP, you can use the `scandir()` function to get a list of all files in the folder, filter out only the image files, and then use `array_rand()` to select a random image from the list. Finally, you can display the selected image using an HTML `<img>` tag.
$folder = 'path/to/images/folder/';
$files = array_diff(scandir($folder), array('..', '.'));
$imageFiles = array_filter($files, function($file) {
return preg_match('/\.(jpg|jpeg|png|gif)$/i', $file);
});
$randomImage = $imageFiles[array_rand($imageFiles)];
echo '<img src="' . $folder . $randomImage . '" alt="Random Image">';
Related questions
-
hidden fields PHP form processing alternative approaches
-
PHP download management script customization
-
Regular expressions PHP functions string manipulation