Home Blog Recursively Delete a Directory and all its Contents with PHP

Recursively Delete a Directory and all its Contents with PHP


PHP’s unlink function will delete a single file and rmdir will delete an empty directory. However, to delete a directory and all contents below it, we require a recursive solution that will hunt down each file through each directory and delete them individually. The first PHP function on this page is one that I use regularly enough; it’ll delete the entire contents of a directory and return either true or false on completion.

What does recursive mean? Recursion, or a recursive function in programming, relates to a procedure that can repeat itself indefinitely (or repeatedly). In our function, we initially scan the directory to be deleted and create an array of the directory root. We iterate over the created array and either apply the same function to a directory or delete a file. The Boolean result is returned on the basis of the target directory being deleted (since it won’t delete if there’s any files left).

The PHP Function

The same modified function can be used to print the contents of an entire directory (with or without the directory structure). Be careful you don’t delete anything you’re not meant to.

How About GLOB?

I also use a GLOB related function myself for various tasks but, in the case of recursive deletions, it doesn’t detect hidden files (so it’s unacceptable for full tree deletions). A scandir option seems to work better most of the time.

PHP’s GLOB is a really funky function for a range of other tasks. To delete files with a specific file extension within a specific directory, you might consider using something to the function below. Given a directory and a string of file types, it’ll delete all the files that match a particular pattern. You could of course have an array of extensions to delete and build that into the recursive function above… but that would defeat the purpose of providing a GLOB example!

The function provides a couple of input corrections; we’ll remove white spaces from the type string (tends to mess up the search), and we’ll add a trailing slash to the dir. The latter might be of use in our first example. Since GLOB is cAsE-SenSitiVe we’ll also add the string of upper-case extensions to our search (after first forcing lower case extensions).


Title: Recursively Delete a Directory and all its Contents with PHP
Description: Recursively Delete a Directory and all its Contents with PHP.
Download: PHP Code (V0.2) | Plugin Page

Shortt URL for this post: http://shor.tt/1XNm



Please enter your comment!
Please enter your name here