Categories: PHP

How to remove a directory and it’s content using PHP

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!

SGH

At the same time, I can’t think of anything more satisfying than sitting in front of TV, eating take-away, lights down low, in my pyjamas and watching crap on TV. Basically, I strive to live a balanced life. Fun. Serious. Fast. Slow. Brainy. Bimbotic. Intense. Lazy. You get the drift.

Recent Posts

Free GG Mug Mockup

GG Mug Mockup designed for logo branding of companies and brands.

6 years ago

Lovtony Font Duo – Modern Sans Serif

A great font/script for creating beautiful logos, posters, wedding invitations, blog posts, social media, and…

6 years ago

Free Men T-Shirt Mockup

Realistic T-Shirt Mockup PSD which you can use freely to showcase your apparel design.

6 years ago

Classic Coffee Mug Mock-up Free PSD

Classic coffee mug Mock-up Free PSD. Free mug mockup PSD to showcase your branding design…

6 years ago

Juliette – Stylish Handwritten Signature Font

Juliette - Stylish Handwritten Signature Font

6 years ago

XXII Aven Sans Serif Font Family

XXII Aven Font Family - a new modern all-caps sans serif font with versatility in creativity.

6 years ago