Was recently working on a project where needed to delete a folder and its sub-folders and files. Here is a snippet that can help you to remove a non-empty directory from the server. It’s a recursive function that deletes the directory with its files, folders and sub-folders.


< ?php
function do_clean($dir,$itself)
{
if ($handle = opendir($dir))
{
$array = array();

    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {

			if(is_dir($dir.$file))
			{
				if(!@rmdir($dir.$file)) // Empty directory? Remove it
				{
                do_clean($dir.$file.'/',$itself); // Not empty? Delete the files inside it
				}
			}
			else
			{
               @unlink($dir.$file);
			}
        }
    }
    closedir($handle);

	if($itself) @rmdir($dir); // allows to delete main directory
}

}


//and here how to call function:
do_clean(/home/path/to/mysite.com/folder_to_delete/);// IMPORTANT: with '/' at the end

?>

Enjoy!

0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

five × four =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like

Genghis – A Single File MongoDB Admin

In order to manage MongoDB databases easily, Genghis, a single-file, self-hosted and web-based solution is pretty handy. It can be installed either as a Ruby gem or as a standalone PHP script.

Calculate folder and subfolders size with PHP

How to read the size of a directory using PHP? Here is a simple function which could help read the size of the directory, number of directories and the number of files in the given directory.

Fast, Effective PHP Compression With .htaccess

PHP compression is an excellent method of conserving bandwidth and reducing client download times. We have already discussed an excellent method for CSS compression, and in this article we share a super-easy technique for compressing all PHP content without editing a single file.