php從文件夾隨機讀取文件的方法
更新時間:2015年06月01日 15:26:39 作者:不吃皮蛋
這篇文章主要介紹了php從文件夾隨機讀取文件的方法,可實現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讀取文件的常見幾種方法
- php fread讀取文件注意事項
- thinkPHP+PHPExcel實現讀取文件日期的方法(含時分秒)
- PHP中讀取文件的幾個方法總結(推薦)
- php文件操作小結(刪除指定文件/獲取文件夾下的文件名/讀取文件夾下圖片名)
- PHP使用fopen與file_get_contents讀取文件實例分享
- PHP讀取文件內容的五種方式
- php讀取文件內容到數組的方法
- PHP中讀取文件的8種方法和代碼實例
- PHP按行讀取文件時刪除換行符的3種方法
- php讀取文件內容的幾種方法詳解
- PHP讀取文件并可支持遠程文件的代碼分享
- php與c 實現按行讀取文件實例代碼
相關文章
PHP使用preg_split和explode分割textarea存放內容的方法分析
這篇文章主要介紹了PHP使用preg_split和explode分割textarea存放內容的方法,結合實例形式分析preg_split和explode函數的功能、使用技巧與文本字符串分割過程中的相關注意事項,需要的朋友可以參考下2017-07-07

