PHP instance sharing all files in the delete directory by recursive implementation _php instance

Source: Internet
Author: User

First Paste code:

Copy Code code as follows:

function Delfile ($dirName) {
if ($handle = Opendir ("$dirName")) {
while (($item = Readdir ($handle))!=false) {
if ($item!= "." && $item!= "...") {
if (Is_dir ("$dirName/$item")) {
Delfile ("$dirName/$item");
Else unlink ("$dirName/$item");
Closedir ($handle);

Delfile ('/home/sources ');

Explain several functions first:

Opendir (): The function opens a directory handle that can be used by Closedir (), Readdir (), and Rewinddir ().

If successful, the function returns a directory stream, otherwise it returns false and an error. You can hide the output of an error by adding "@" in front of the function name. For example $dir=@ opendir ("image");

Readdir (): Returns an entry in a table of contents handle opened by the Opendir function that returns the file names in the folder sequentially in the order that they are sorted in the file system.

Id_dir (): detects whether the parameter file is a directory, or returns TRUE.

Un_link (): Deletes the development document.

So the idea of program execution is: The function calls the home directory, and then sequentially detects if each file is a directory, recursively calls the function if it is a directory, and deletes the file that is not a directory until all the files have been traversed.

This program only implements the deletion of the contents of the folder, and does not delete the folder itself, if you want to do this, add the following code to:

Copy Code code as follows:

RmDir ($dirName);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.