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

青灯夜游
Release: 2023-04-08 15:48:01
forward
2795 people have browsed it

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");
}
Copy after login

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);
Copy after login

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);
Copy after login

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!

Related labels:
php
source:csdn.net
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template