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">';
Keywords
Related Questions
- What are the potential pitfalls of not properly handling character encoding in PHP when working with HTML and MySQL?
- Why is it recommended to use a Mailer class instead of the mail() function in PHP for sending emails securely?
- How can PHP arrays, implode, and explode be used to split and encode input data more efficiently?