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 在变量定义中不需要(或不支持)明确的类型定义;变量类型是根据使用该变量的上下文所决定的。也就是说,如果把一个字符串值赋给变量 var,var 就成了一个字符串。如果又把一个整型值...

php实现字符串翻转的方法

本文实例讲述了php实现字符串翻转的方法。分享给大家供大家参考。具体实现方法如下: <?php header("content-type:text/html;chars...

PHP删除特定数组内容并且重建数组索引的方法.

复制代码 代码如下: $a = array('a','b','c','d'); unset($a[2]); print_r($a); 但是这种方法的最大缺点是没有重建数组索引. 经过查资...

PHP中散列密码的安全性分析

本文实例讲述了PHP中散列密码的安全性。分享给大家供大家参考,具体如下: php的基本哈希函数已经不再安全? php手册中有专门的一个部分来介绍这个问题 http://php.net/m...

Windows下安装Memcached的步骤说明

(其实在Windows下安装还是比较简单的) 源码包准备: 1,memcached 1.2.1 for Win32 binaries 这个是 Win32 服务器端的 memcached...