function read_comments() {
if (!is_dir(COMMENT_DIR) || !is_readable(COMMENT_DIR))
return false;
$file_list = glob(COMMENT_DIR . '*20130721T161046-1262521337.txt');
$comments = array();
foreach ($file_list as $file_name) {
if (($data = file($file_name)) !== false) {
$comments[] = unserialize_comment($data);
}
}
return $comments;}
我如何能够在glob()中放置一个随机文件名? foreach()一直给我带来麻烦。
答案 0 :(得分:1)
此函数返回给定文件夹中的随机文件。它还允许扩展过滤。
function RandomFile($folder='COMMENT_DIR', $extensions='.txt'){
// 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!');
}
}
并使用
$file_list = glob($folder . $rand_file);