Home  >  Article  >  Backend Development  >  How to delete all folders and files under a path in PHP?

How to delete all folders and files under a path in PHP?

青灯夜游
青灯夜游forward
2020-05-04 10:59:202778browse

PHP How to delete all folders and files under a path? The following article will introduce to you how to delete all folders and files under a path in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to delete all folders and files under a path in PHP?

Function used:

  • scandir($path) Traverses all files in a folder and Return an array.

  • unlink($filename) Delete the file.

  • rmdir($path) Delete only empty folders

Code:

Delete a single File

$file = "./aa/aas.txt";
if (!unlink($file))
{
	echo ("Error deleting $file");
}
else
{
	echo ("Deleted $file");
}

Method to delete all folders and files under a path 1

$path = "./aa";
function deleteDir($dir)
{
    if (!$handle = @opendir($dir)) {
        return false;
    }
    while (false !== ($file = readdir($handle))) {
        if ($file !== "." && $file !== "..") {       //排除当前目录与父级目录
            $file = $dir . '/' . $file;
            if (is_dir($file)) {
                deleteDir($file);
            } else {
                @unlink($file);
            }
        }

    }
    @rmdir($dir);
}
deleteDir($path);

Method to delete all folders and files under a path 2

//设置需要删除的文件夹
$path = "./aa";
//清空文件夹函数和清空文件夹后删除空文件夹函数的处理
function deldir($path){
   //如果是目录则继续
   if(is_dir($path)){
    //扫描一个文件夹内的所有文件夹和文件并返回数组
	   $p = scandir($path);
	   foreach($p as $val){
	    //排除目录中的.和..
	    if($val !="." && $val !=".."){
	     //如果是目录则递归子目录,继续操作
		    if(is_dir($path.'/'.$val)){
		      //子目录中操作删除文件夹和文件
		      deldir($path.'/'.$val);
		      //目录清空后删除空文件夹
		      @rmdir($path.'/'.$val);
		    }else{
		      //如果是文件直接删除
		      unlink($path.'/'.$val);
		    }
		}
	   }
	}
  }
 //调用函数,传入路径
 deldir($path);

Recommended learning : PHP video tutorial

The above is the detailed content of How to delete all folders and files under a path in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete