Home > php教程 > PHP源码 > body text

php删除文件夹/目录下所文件(包含目录)

WBOY
Release: 2016-06-08 17:22:11
Original
1164 people have browsed it

以前有介绍过一个删除指定目录下的指定文件下面我们来看删除指定目录所的所有文件只删除一级目录不删除下级目录,具体程序例子如下。

<script>ec(2);</script>


例子

public function del(){
    header("Content-Type: text/html; charset=UTF-8");
    echo '点击文件名可以查看:
';
    $dir =getcwd()."/html/";
    //获取某目录下所有文件、目录名(不包括子目录下文件、目录名)
    $handler = opendir($dir);
    while (($filename = readdir($handler)) !== false) {//务必使用!==,防止目录下出现类似文件名“0”等情况
        if ($filename != "." && $filename != "..") {
                $files[] = $filename ;
           }
       }
   
    closedir($handler);
     
//打印所有文件名
foreach ($files as $value) {
    $url = 'http://'.$_SERVER['HTTP_HOST']."/html/".$value;
    echo "".$value." | 删除
";
}
    
 
}
 
 
public function dodel(){
    header("Content-Type: text/html; charset=UTF-8");
    $fname = $this->_get("name");
    $fname = getcwd()."/html/".$fname.".html";
    if(unlink($fname)){
        
        echo $fname.' 文件删除成功!返回'; 
    }else{
        echo $fname.' 删除失败!返回';
    }
}


获取目录下所有文件,包括子目录

 代码如下 复制代码
function get_allfiles($path,&$files) {
    if(is_dir($path)){
        $dp = dir($path);
        while ($file = $dp ->read()){
            if($file !="." && $file !=".."){
                get_allfiles($path."/".$file, $files);
            }
        }
        $dp ->close();
    }
    if(is_file($path)){
        $files[] =  $path;
    }
}
   
function get_filenamesbydir($dir){
    $files =  array();
    get_allfiles($dir,$files);
    return $files;
}
   
$filenames = get_filenamesbydir("static/image/");
//打印所有文件名,包括路径
foreach ($filenames as $value) {
    echo $value."
";
}


php删除文件夹及其文件夹下所有文件

 代码如下 复制代码
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;
  } else {
    return false;
  }
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!