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 was not found! Very strange! '); } // Return the random file: Return $ folder. $ files [$ rand]; } // Usage demonstration: // "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 |