Simple way to get random image or any file from folder using PHP, get random image from directory and display it, PHP example code and script download, and demo.
How To Get Random Image From Folder Using PHP
Using scandir() function we will get all files in our folder, and using count() function we will get count of files in our folder, and using rand() function we will display random image or any random file.
Demo
Get Random Image Function
Using Qassim_Random_File() function we will get random image from folder, and you can use it to get any “random” file:
<?php /* Random File Function Written By: Qassim Hassan Website: wp-time.com Twitter: @QQQHZ */ function Qassim_Random_File($folder_path = null){ if( !empty($folder_path) ){ // if the folder path is not empty $files_array = scandir($folder_path); $count = count($files_array); if( $count > 2 ){ // if has files in the folder $minus = $count - 1; $random = rand(2, $minus); $random_file = $files_array[$random]; // random file, result will be for example: image.png $file_link = $folder_path . "/" . $random_file; // file link, result will be for example: your-folder-path/image.png return '<a href="'.$file_link.'" target="_blank" title="'.$random_file.'"><img src="'.$file_link.'" alt="'.$random_file.'"></a>'; } else{ return "The folder is empty!"; } } else{ return "Please enter folder path!"; } } ?>
Usage:
<?php echo Qassim_Random_File("your-folder-name"); // display random image! ?>
Change “your-folder-name” to your folder name.
Note
You can use Qassim_Random_File() function to get any random file, for example to get random MP3, just replace this line:
return '<a href="'.$file_link.'" target="_blank" title="'.$random_file.'"><img src="'.$file_link.'" alt="'.$random_file.'"></a>';
To this line:
return '<audio controls><source src="'.$file_link.'" type="audio/mpeg"></audio>';
Now upload MP3 files to your folder! Enjoy.
Download
You can download demo script.
2 Comments
Jose
Hi, Its possible to use this in a WP widget and when users click it show another image without refresh the page?
Thanks.
Qassim Hassan
Yes you can do it, read: https://wp-time.com/wordpress-random-image/