Deletion method: 1. Use the scandir() function and foreach statement to traverse all files and folders in the specified directory; 2. Use recursive method to delete all files and folders in the specified directory one by one. The directory becomes an empty directory; 3. Use the "rmdir (directory path)" statement to delete the specified directory.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
You can use the rmdir() function in PHP Delete the specified directory. The syntax format of this function is as follows:
rmdir(string $dirname[, resource $context])
Among them, the parameter $dirname is the path of the directory to be deleted; $context is an optional parameter, used to specify the environment of the file handle.
Note: When using the rmdir() function to delete the specified directory, the directory must be empty and must have corresponding permissions. TRUE is returned when the function is executed successfully, and FALSE is returned if the execution fails. If a non-empty directory is deleted, an E_WERNING level error will be generated.
So if you need to use rmdir() to delete a non-empty directory, what should you do?
We can traverse all files and folders in this directory and delete all files and folders in this directory one by one recursively. The following is demonstrated through sample code:
<?php function deldir($path){ //如果是目录则继续 if(is_dir($path)){ //扫描一个文件夹内的所有文件夹和文件并返回数组 $p = scandir($path); //如果 $p 中有两个以上的元素则说明当前 $path 不为空 if(count($p)>2){ foreach($p as $val){ //排除目录中的.和.. if($val !="." && $val !=".."){ //如果是目录则递归子目录,继续操作 if(is_dir($path.$val)){ //子目录中操作删除文件夹和文件 deldir($path.$val.'/'); }else{ //如果是文件直接删除 unlink($path.$val); } } } } } //删除目录 return rmdir($path); } //设置需要删除的文件夹 $path = "./test/"; //调用函数,传入路径 deldir($path); ?>
Description:
scandir() function returns an array containing all files and directories in the specified directory.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to delete non-empty directories using php rmdir(). For more information, please follow other related articles on the PHP Chinese website!