一、遍历 opendir
具体函数我就不解释了,直接看代码理解:
<?php header("Content-Type:Text/html;charset=utf8"); $dir = 'd:/test/'; //将路径赋值给变量 if(is_dir($dir)){ //判断该变量是不是一个目录 if($dh = opendir($dir)){ //打开目录 //读取文件,当文件不是空的时候,循环读出文件 while(($file = readdir($dh))!==false){ if($file == ''||$file == '..'||$file == '.'){ continue; //如果文件中有‘’和“..”就跳出 } echo "file:{$file}"."<br>"; //输出文件名 echo "filetype:".filetype($dir.$file)."<br>"; } } closedir($dh); //关闭目录 } ?>
在我的D:/test/目录下的结果:
现在我们来写一个函数,遍历指定目录下所有文件,如果遇到目录,继续遍历目录下的文件。
<?php header("Content-Type:Text/html;charset=utf8"); $dir = 'd:/test/'; //将路径赋值给变量 function scanAll($dir){ if(is_dir($dir)){ //判断该变量是不是一个目录 echo "DIR:".$dir."<br>"; $child = scandir($dir) ; //列出指定路径中的文件和目录并赋值给$child foreach($child as $c){ if($c !== '.' && $c !== '..'){ //不等于当前目录且不等于父目录 scanAll($dir.'/'.$c); //遍历递归 } } } if(is_file($dir)){ echo 'File:'.$dir."<br>"; } } scanAll($dir); ?>
2、复制目录 copy($source,$dest)
<?php //目录复制 header("Content-Type:Text/html;charset=utf8"); function copydir($sourceDir,$destDir){ if(!is_dir($sourceDir)){ return false; } if(!is_dir($destDir)){ if(!mkdir($destDir)){ return false; } } $dir = opendir($sourceDir); if(!$dir){ return false; } while(false !== ($file=readdir($dir))){ if($file != '.' && $file != '..'){ if(is_dir($sourceDir.'/'.$file)){ if(!copydir($sourceDir.'/'.$file,$destDir.'/'.$file)) { return false; } }else{ if(!copy($sourceDir.'/'.$file,$destDir.'/'.$file)){ } } } } closedir($dir); return true; }
3、删除目录 --unlink($path)
<?php //删除目录 header("Content-Type:Text/html;charset=utf8"); function deldir($dir){ $dh = opendir($dir); while($file = readdir($dh)){ if($file !='.' && $file != '..'){ $fullpath = $dir.'/'.$file; if(!is_dir($fullpath)){ unlink($fullpath); }else{ deldir($fullpath); } } } closedir($dh); if(rmdir($dir)){ return true; } return false; }