php从文件夹随机读取文件的方法

yipeiwu_com5年前PHP代码库

本文实例讲述了php从文件夹随机读取文件的方法。分享给大家供大家参考。具体实现方法如下:

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];
}

//用法演示:
// "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

希望本文所述对大家的php程序设计有所帮助。

相关文章

大家都应该掌握的PHP关联数组使用技巧

在使用 PHP 进行开发的过程中,或早或晚,您会需要创建许多相似的变量,这时候你可以把数据作为元素存储在数组中。数组中的元素都有自己的 ID,因此可以方便地访问它们。 关联数组 关联数组...

php操作MongoDB类实例

本文实例讲述了php操作MongoDB类的方法。分享给大家供大家参考。具体如下: 1. MyMongo.php文件: <?php /** * 仿写CI的MongoDB...

分享一下贝贝成长进度的php代码

主要功能是根据贝贝的出生日期来显示贝贝现在多大了,实时显示贝贝的成长。 用当前时间减去出生的日期,但是可以显示出来几岁,几个月,和几天。 天的算法有点问题,没有考虑到大小月和2月份。 复...

PHP正则删除html代码中a标签并保留标签内容的方法 原创

本文实例讲述了PHP正则删除html代码中a标签并保留标签内容的方法。分享给大家供大家参考,具体如下: 一、问题: 有HTML代码如: <div>欢迎访问【宜配屋www....

php 出现Strict Standards: Only variables should be passed by reference in的解决方法

这个问题多半是因为引用传递参数引起的,解决办法一是修改代码不使用引用传递;另一个办法是修改php配置文件,修改error_reporting 其值改为error_reporting =...