Home  >  Article  >  Backend Development  >  How to delete a folder and all files under it in php

How to delete a folder and all files under it in php

coldplay.xixi
coldplay.xixiOriginal
2020-11-03 16:00:094862browse

php method to delete a folder and all files under the folder: first create a new recursive function to perform the folder deletion operation; then within the recursive function, execute a while loop and use the unlink method to delete the files in the folder. Until there are no files in the folder; finally jump out of the while loop and use the rmdir method to delete the files.

How to delete a folder and all files under it in php

Related learning recommendations: php programming (video)

phpHow to delete a folder and all files under the folderMethod:

1. Create a new php file named test.php to explain how to delete php folder and all files under the folder.

2. In the test.php file, create a removeDir() function whose parameter is $dirName (the name of the directory to be deleted).

3. In the removeDir() function, use the is_dir() method to determine whether $dirName is a directory. If it is not a directory, return false. If it is a directory, use the opendir() method to open the directory.

How to delete a folder and all files under it in php

4. In the removeDir() function, use the while() method to read the folder. If there is a file under the folder, use the unlink() method to delete the file; If there is a non-empty folder under the folder, use the folder as a parameter, recursively call the function again to delete the files in the folder, until it is an empty folder (that is, there are no files in the folder), and jump out of the while() loop. Use the rmdir() method to delete a folder.

How to delete a folder and all files under it in php

5. In the test.php file, use the header() method to set the encoding of the file execution to utf8 to avoid garbled characters when outputting Chinese.

How to delete a folder and all files under it in php

6. In the test.php file, define a $path variable to save the folder to be deleted, and delete the folder and its contents by calling the removeDir() function. All files and directories. Use the if statement to judge the deletion result and output a prompt whether the deletion is successful or not.

How to delete a folder and all files under it in php

#7. Execute the test.php file in the browser and view the output results.

How to delete a folder and all files under it in php

The above is the detailed content of How to delete a folder and all files under it in php. For more information, please follow other related articles on the PHP Chinese website!

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