php從文件夾隨機(jī)讀取文件的方法
更新時間:2015年06月01日 15:26:39 作者:不吃皮蛋
這篇文章主要介紹了php從文件夾隨機(jī)讀取文件的方法,可實現(xiàn)php從指定的目錄隨機(jī)讀取文件及設(shè)置參數(shù)進(jìn)行文件過濾的功能,需要的朋友可以參考下
本文實例講述了php從文件夾隨機(jī)讀取文件的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
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程序設(shè)計有所幫助。
您可能感興趣的文章:
- php遍歷、讀取文件夾中圖片并分頁顯示圖片的方法
- PHP讀取文件的常見幾種方法
- php fread讀取文件注意事項
- thinkPHP+PHPExcel實現(xiàn)讀取文件日期的方法(含時分秒)
- PHP中讀取文件的幾個方法總結(jié)(推薦)
- php文件操作小結(jié)(刪除指定文件/獲取文件夾下的文件名/讀取文件夾下圖片名)
- PHP使用fopen與file_get_contents讀取文件實例分享
- PHP讀取文件內(nèi)容的五種方式
- php讀取文件內(nèi)容到數(shù)組的方法
- PHP中讀取文件的8種方法和代碼實例
- PHP按行讀取文件時刪除換行符的3種方法
- php讀取文件內(nèi)容的幾種方法詳解
- PHP讀取文件并可支持遠(yuǎn)程文件的代碼分享
- php與c 實現(xiàn)按行讀取文件實例代碼
相關(guān)文章
解析WordPress中的post_class與get_post_class函數(shù)
這篇文章主要介紹了WordPress中的post_class與get_post_class函數(shù),包括post_class()的PHP源碼的相應(yīng)介紹,需要的朋友可以參考下2016-01-01
PHP的Laravel框架中使用AdminLTE模板來編寫網(wǎng)站后臺界面
這篇文章主要介紹了PHP的Laravel框架中使用AdminLTE模板來編寫網(wǎng)站后臺的方法,AdminLTE基于BootStrap,能幫助快速創(chuàng)建網(wǎng)站后臺管理面板界面,需要的朋友可以參考下2016-03-03
PHP面向?qū)ο蟪绦蛟O(shè)計之多態(tài)性的應(yīng)用示例
這篇文章主要介紹了PHP面向?qū)ο蟪绦蛟O(shè)計之多態(tài)性的應(yīng)用,結(jié)合具體實例形式分析了php面向?qū)ο蟪绦蛟O(shè)計中關(guān)于多態(tài)性的概念、原理、相關(guān)使用技巧及注意事項,需要的朋友可以參考下2018-12-12
PHP實現(xiàn)機(jī)器學(xué)習(xí)之樸素貝葉斯算法詳解
這篇文章主要介紹了PHP實現(xiàn)機(jī)器學(xué)習(xí)之樸素貝葉斯算法,結(jié)合實例形式詳細(xì)分析了樸素貝葉斯算法的概念、原理及php實現(xiàn)技巧,需要的朋友可以參考下2017-12-12

