PHP Random read files from the folder method, _php tutorial

Source: Internet
Author: User

How PHP randomly reads files from a folder,


The example in this article describes how PHP randomly reads files from a folder. Share to everyone for your reference. The implementation method is as follows:

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 (!PR Eg_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 extensionsprint 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 the just//contain numbers (like BACKUP.1, BACKUP.2) print randomfile (' test_files/') , ' [0-9]+ ');//returns BACKUP.7

I hope this article is helpful to everyone's PHP programming.

http://www.bkjia.com/PHPjc/1011259.html www.bkjia.com true http://www.bkjia.com/PHPjc/1011259.html techarticle php Random read files from the folder method, this article describes the PHP from the folder random Read file method. Share to everyone for your reference. The concrete implementation method is as follows: Functio ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.