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

yipeiwu_com6年前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下判断数组中是否存在相同的值array_unique

array_unique(PHP 4 >= 4.0.1, PHP 5) array_unique -- 移除数...

PHP中if和or运行效率对比

本文实例讲述了PHP中if和or运行效率对比。分享给大家供大家参考。具体实现方法如下: 对if和or的运行效率进行了实例说明,感兴趣的朋友可以测试一下,这里我测试了的结果是or 比if效...

php session的应用详细介绍

php session的应用详细介绍

php session高级应用 session在web技术中非常重要,由于网页是一种无状态的连接程序,因此无法得知用户的浏览状态。通过session则可以记录用户的有关信息,以供用户再次...

php 随机排序广告的实现代码

投放广告的人都很关注他的广告会放在哪个位置, 因为这可能影响点击次数, 甚至是否在第一屏显示. 就这个问题, 其实很容易解决, 只要随机显示广告即可. 代码如何实现? 在这我推荐两种随机...

php curl获取网页内容(IPV6下超时)的解决办法

原因:在程序中我对curl获取内容都作了较为严格的超时限制,所以就会造成无法获取内容的问题。解决方法:设置默认访问为ipv4。php的curl设置方法如下:复制代码 代码如下:<?...