PHP实现递归循环每一个目录程序
要遍历一个文件夹里面的所有目录,列出里面所有的文件,PHP本身自带的有一个readdir的函数,不过只能读取当前的目录,根据这个函数,我写了另外一个函数,用来实现我的需求,代码如下:
<?php class listdir{ var $depth ; var $dirname ; var $list ; var $tostring ; function listdir( $dir ){ $this ->dirname= $dir ; $this ->depth=0; $this ->tostring=]"; } //把结果保存进多维数组 function getlist( $dir =]"){ if ( $dir ==]") $dir = $this ->dirname; $d =@dir( $dir ); while (false!==( $item = $d ->read())) { if ( $item !=].]&& $item !=]..]) { $path = $dir .]/]. $item ; if ( is_dir ( $path )){ $this ->depth+=1; $this ->getlist( $path ); } else { $this ->list[ $this ->depth][]= $item ; } } } $this ->list[ $this ->depth][ 'directory' ]= $dir ; $this ->depth-=1; $d ->close(); return $this ->list; } //字符窜化结果 function tostring( $dir =]"){ if ( $dir ==]") $dir = $this ->dirname; $d =@dir( $dir ); $this ->tostring.=]<UL>n]; $this ->tostring.=]Directory:]. $dir .]n]; while (false!==( $item = $d ->read())) { if ( $item !=].]&& $item !=]..]) { $path = $dir .]/]. $item ; if ( is_dir ( $path )){ $this ->depth+=1; $this ->tostring( $path ); } else { $this ->tostring.=]<LI>]. $item .]</LI>n]; } } } $this ->depth-=1; $d ->close(); $this ->tostring.=]</UL>n]; return $this ->tostring; } } $wapdir =]jquery]; $d = new listdir( $wapdir ); echo $d ->tostring(); ?>要删除一个空的目录很简单~一个,rmdir() 函数就可以搞定,但是要删除一个非空目录,将不能进行快速的删除,必须先将目录中文件删除,但是目录里可能还会有子目录所以要进行递归删除~下面是我的例子~代码如下:
<?php function deletedir( $dir ){ if (!handle=@opendir( $dir )){ //检测要打开目录是否存在 die ( "没有该目录" ); } while (false !==( $file =readdir( $handle ))){ if ( $file !== "." && $file !== ".." ){ //排除当前目录与父级目录 $file = $dir .DIRECTORY_SEPARATOR. $file ; if ( is_dir ( $file )){ deletedir( $file ); } else { if (@unlink( $file )){ echo "文件<b>$file</b>删除成功。<br>" ; } else { echo "文件<b>$file</b>删除失败!<br>" ; } } } if (@ rmdir ( $dir )){ echo "目录<b>$dir</b>删除成功了。<br>n" ; } else { echo "目录<b>$dir</b>删除失败!<br>n" ; } } //测试程序 $dir = "/var/www/test" ; deletedir( $dir ); ?>查看更多关于PHP实现递归循环每一个目录程序 - php文件操作的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did27880