php遍历目录与文件夹的几种方法
遍历目录或遍历目录下指定类型的文件,这是每一个童鞋在写程序的时候难免会用到的,PHP本身也提供了很多非常有用的函数,正确地使用它们,不会有错,下面就我个人学习过程中的一些总结.
本函数可以列出指定目录下所有的文件,包括子目录下的,代码如下:
function getfiles( $path ){ foreach (scandir( $path ) as $afile ) { if ( $afile == '.' || $afile == '..' ) continue ; if ( is_dir ( $path . '/' . $afile )) { getfiles( $path . '/' . $afile ); } else { echo $path . '/' . $afile . '<br />' ; } } } //简单的demo,列出当前目录下所有的文件 getfiles(__DIR__);scandir() 是返回指定目录下所有的文件和目录组成的数组,在PHP中,还提供了一个非常强大的函数glob(),glob()有2个参数,至于第2个参数是可选的,稍后再讲,直接来看,用glob()怎么遍历目录的.
可以看出,glob()返回的内容中已经过滤掉了'.'和'..',其中*表示遍历目录下所有文件,相应的,如果改为*.txt,则会遍历目录下所的txt文件,是不是很方便呢?它的方便之处可不止这一点,代码如下:
function getfiles( $path ){ foreach ( glob ( $path ) as $afile ){ if ( is_dir ( $afile )) { getfiles( $afile . '/*' ); } else { echo $afile . '<br />' ; } } } //简单的demo,列出当前目录下所有的文件 getfiles(__DIR__);0既然说用 *.txt,就会遍历目录下所的txt文件,那如果我想让它同时遍历某几种格式的文件呢?怎么办?肯定有童鞋想到用数组了,然后很快的写出来替换进去{*.txt,*.jpg,*.zip,...},当然也很快地发现,程序返回false,什么都得不到,不要失望,这涉及到了刚才所说的第2个可选参数,这个参数是用来改变glob的行为的,具体都有些什么,可以查阅PHP手册,这里不多讲,只说一个GLOB_BRACE,这是用来扩充 {a,b,c,...} 来匹配 'a','b' 或 'c',...的,用法如下:
foreach(glob($path.'/{*.txt,*.jpg,*.zip,...}', GLOB_BRACE) as $fileName){...}
至于完整的遍历目录下所有的指定文件类型函数,我们可以看下面实例.
遍历文件夹及子文件夹所有文件,代码如下:
<html> <body> <?php function traverse( $path = '.' ) { $current_dir = opendir( $path ); //opendir()返回一个目录句柄,失败返回false while (( $file = readdir( $current_dir )) !== false) { //readdir()返回打开目录句柄中的一个条目 $sub_dir = $path . DIRECTORY_SEPARATOR . $file ; //构建子目录路径 if ( $file == '.' || $file == '..' ) { continue ; } else if ( is_dir ( $sub_dir )) { //如果是目录,进行递归 echo 'Directory ' . $file . ':<br>' ; traverse( $sub_dir ); } else { //如果是文件,直接输出 echo 'File in Directory ' . $path . ': ' . $file . '<br>' ; } } } traverse( 'xxtt' ); ?> </body> </html>一些常用的实例,代码如下:
<?php $dir = "E:/video" ; //这里输入其它路径 //PHP遍历文件夹下所有文件 $handle =opendir( $dir . "." ); echo "文件:<br>" ; while (false !== ( $file = readdir( $handle ))) { if ( $file != "." && $file != ".." ) { echo $file ; //输出文件名 } } closedir ( $handle ); ?>用了这段代码遍历所有文件,我把所有文件名存为一个数组,代码如下:
<?php $s = explode ( "/n" ,trim(`dir/b e: //video`)); print_r( $s ); ?> <?php $dir = "E:/video" ; //这里输入其它路径 //PHP遍历文件夹下所有文件 $handle =opendir( $dir . "." ); echo "文件:<br>" ; while (false !== ( $file = readdir( $handle ))) { if ( $file != "." && $file != ".." ) { $file = $file . ',' ; //输出文件名 $file = explode ( ',' , $file ); } } print_r( $file ); //输出的就是数组了 closedir ( $handle ); ?> <?php $dir = "." ; //这里输入其它路径 //PHP遍历文件夹下所有文件 $handle =opendir( $dir . "." ); echo "文件:<br>" ; //定义用于存储文件名的数组 $array_file = array (); while (false !== ( $file = readdir( $handle ))) { if ( $file != "." && $file != ".." ) { $array_file [] = $file ; //输出文件名 } } closedir ( $handle ); print_r( "<pre>" ); print_r( $array_file ); print_r( "</pre>" ); ?>查看更多关于php遍历目录与文件夹的几种方法 - php文件操作的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did27844