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水印和缩略图制作代码,使用面向对象的方法来实现常见图片格式jpg,png,gif的水印和缩略图的制作,供大家参考,具体内容如下 <?php h...

纯php生成随机密码

纯php生成随机密码

php生成一个随机的密码,方便快捷,可以随机生成安全可靠的密码。 分享代码如下 <?php header("Content-type:text/html;chars...

php join函数应用

复制代码 代码如下: $key = array(); $val = array(); foreach ($_POST as $k=>$v) { $key[] = '`'.strip...

php 执行系统命令的方法

代码如下: 复制代码 代码如下:#include <stdio.h> #include <stdlib.h> #include <sys/types.h&g...

PHP中创建图像并绘制文字的例子

PHP中创建图像并绘制文字的例子

在图像中显示的文字也需要按坐标位置画上去。在PHP中不仅支持比较多的字体库,而且提供了非常灵活的文字绘制方法。例如,在图中绘制缩放、倾斜、旋转的文字等。可以使用imageString()...