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 the folder '. $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 is 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 that just Contain numbers (like BACKUP.1, BACKUP.2) Print randomfile (' test_files/', ' [0-9]+ '); Returns BACKUP.7 |