This example describes how PHP randomly reads files from a folder. Share to everyone for your reference. The implementation methods are as follows:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 This is the |
function randomfile ($folder = ', $extensions = '. * ') {//fix path: $folder = Trim ($folder); $folder = ($folder = = ")? './': $folder; Check Folder:if (!is_dir ($folder)) {die (' Invalid folder given! ');}//Create files Array $files = array (); Open Directory if ($dir = @opendir ($folder)) {//Go trough all files:while ($file = Readdir ($dir)) {if (!preg_match ('/^ . +$/', $file) and Preg_match ('/. $extensions. ') $/', $file)) {//Feed the array: $files [] = $file;}} Close directory Closedir ($DIR); else {die (' could not open '. $folder. ');} if (count ($files) = = 0) {die (' No files where found:-('); Seed Random Function:mt_srand (double) microtime () *1000000); Get an random index: $rand = Mt_rand (0, Count ($files)-1); Check Again:if (!isset ($files [$rand])) {die (' Array index ' not found! very strange! ');//Return the random file: Return $folder. $files [$rand]; //Usage Demo://"jpg|png|gif" matches all files with these extensions print randomfile (' test_images/', ' jpg|png|gif '); Returns Test_07.gif//". *" matches all extensions (all files) print randomfile (' test_files/', '. * '); Returns Foobar_1.zip//"[0-9]+" matches all extensions then just//contain numbers (like BACKUP.1, BACKUP.2) print Ra Ndomfile (' test_files/', ' [0-9]+ '); Returns BACKUP.7 |
I hope this article will help you with your PHP programming.