How to delete non-empty directories using php rmdir()

青灯夜游
Release: 2023-03-13 08:28:01
Original
3572 people have browsed it

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.

How to delete non-empty directories using php rmdir()

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

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 emptyand 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:

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

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!

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
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!