PHP获取文件夹下随机一个文件

起因:

    商城上面会员头像不是很完整,我就想整一个头像包,为没有头像的随机选择一个,所以需要随机获取一张图片。


   QQ图片20150929104900.png 

    /**
     * 随机获取图片
     * @author Yusure  
     * @date   2015-09-29
     * @param  [param]
     * @param  string     $folder     图片目录路径
     * @param  string     $extensions 后缀
     */
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 $files[$rand];
    }


评论