How to delete directory in php

藏色散人
Release: 2023-03-13 15:02:01
Original
4597 people have browsed it

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.

How to delete directory in php

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])
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 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.

Copy after login

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

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:

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

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!

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!