Home > Article > Backend Development > How to delete directory in php
php method to delete a directory: 1. Create a PHP sample file; 2. Find the directory that needs to be deleted; 3. Use the rmdir() function to delete the specified directory.
The operating environment of this article: windows7 system, PHP version 7.1, DELL G3 computer
How to delete the directory in php?
PHP rmdir(): Delete directory
Similar to ordinary files, if you confirm that a directory will no longer be used, you can delete the directory. In PHP, you can use the rmdir() function to delete a 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 a 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.
[Example] Use the rmdir() function to delete the specified directory.
<?php $dir = './test'; if(is_dir($dir)){ if(rmdir($dir)) echo '目录删除成功!'; }else{ echo "目录不存在!"; } ?>
To run the above code, first make sure that the test directory is empty, otherwise the following error will occur:
Warning: rmdir(./test): Directory not empty in D:\WWW\index.php on line 4
What should I do if I want to delete a directory that is not empty? We can traverse all the files and folders in this directory and delete all the 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); ?>
Recommended learning: " PHP video tutorial》
The above is the detailed content of How to delete directory in php. For more information, please follow other related articles on the PHP Chinese website!