php glob()函数 遍历目录或文件夹
作者:Alpha时间:2017-09-14 阅读数:2962 +人阅读
定义和用法
glob() 函数返回匹配指定模式的文件名或目录。
该函数返回一个包含有匹配文件 / 目录的数组。如果出错返回 false。
例子 1
<?php print_r(glob("*.txt")); ?>
输出类似:
Array ( [0] => target.txt [1] => source.txt [2] => test.txt [3] => test2.txt )
例子 2
<?php print_r(glob("*.*")); ?>
输出类似:
Array ( [0] => contacts.csv [1] => default.php [2] => target.txt [3] => source.txt [4] => tem1.tmp [5] => test.htm [6] => test.ini [7] => test.php [8] => test.txt [9] => test2.txt )
php遍历目录我们很多朋友会想到是opendir与readdir,这样就可以遍历目录并显示文件,但在php中有一个更简洁的遍历目录的函数glob估计很少有人知道此函数,不过我觉得比起opendir与readdir要简单多了.
PHP glob函数的使用:glob—寻找与模式匹配的文件路径.
<?php $fileList=glob('*.*'); for ($i=0; $i<count($fileList); $i++) { echo $fileList[$i].'<br />'; } $fileList2=glob('images/*'); for ($i=0; $i<count($fileList2); $i++) { echo $fileList2[$i].'<br />'; } $fileList3=glob('*'); for ($i=0; $i<count($fileList3); $i++) { echo $fileList3[$i].'<br />'; } ?>
第一种:glob函数的参数里面是:*.* ,意思是扫描当前目录下的文件,不包括文件夹,返回的是一个数组,以下二种情况一样.
第二种:glob函数的参数里面是:images/*,是指定目录扫描所有的文件,包括文件夹,也可以扫描指定的文件类型,如:images/*.jpg;注意,如果只输入:images只会返回该文件夹名称,如果只输入:images/则什么也不会返回.
第三种:glob函数的参数里面是:*,可以扫描出当前目录下的所有文件、目录及子目录的文件.
好我们再看看opendir与readdir遍历目录,代码如下:
<?php /********************** 一个简单的目录递归函数 第一种实现办法:用dir返回对象 ***********************/ function tree($directory) { $mydir = dir($directory); echo "<ul>\n"; while($file = $mydir->read()) { if((is_dir("$directory/$file")) AND ($file!=".") AND ($file!="..")) { echo "<li><font color=\"#ff00cc\"><b>$file</b></font></li>\n"; tree("$directory/$file"); } else echo "<li>$file</li>\n"; } echo "</ul>\n"; $mydir->close(); } //开始运行 echo "<h2>目录为粉红色</h2><br>\n"; tree("./nowamagic"); /*********************** 第二种实现办法:用readdir()函数 ************************/ function listDir($dir) { if(is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { if((is_dir($dir."/".$file)) && $file!="." && $file!="..") { echo "<b><font color='red'>文件名:</font></b>",$file,"<br><hr>"; listDir($dir."/".$file."/"); } else { if($file!="." && $file!="..") { echo $file."<br>"; } } } closedir($dh); } } } //开始运行 listDir("./nowamagic"); ?>
本站所有文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:595397166@qq.com
上一篇:没有了
下一篇:PHP文件目录处理技术