Remove all files, folders and their subfolders with php

user546774 picture user546774 · Jul 23, 2012 · Viewed 61.2k times · Source

I need a script which can remove a whole directory with all their subfolders, files and etc. I tried with this function which I found in internet before few months ago but it not work completely.

function deleteFile($dir) {
    if(substr($dir, strlen($dir)-1, 1) != '/') { 
        $dir .= '/'; 
    }
    if($handle = opendir($dir)) { 
        while($obj = readdir($handle)) { 
            if($obj != '.' && $obj != '..') { 
                if(is_dir($dir.$obj)) { 
                    if(!deleteFile($dir.$obj)) {
                        echo $dir.$obj."<br />";
                        return false;
                    }
                }
                elseif(is_file($dir.$obj)) { 
                    if(!unlink($dir.$obj)) {
                        echo $dir.$obj."<br />";
                        return false;
                    }
                }
            }
        }
        closedir($handle); 
        if(!@rmdir($dir)) {
            echo $dir.'<br />';
            return false;
        }
        return true;
    }
    return true;
}

For the test I use a unpacked archive of prestashop and I try to delete the folder where archive is unpacked but it doesn't work.

/home/***/public_html/prestashop/img/p/3/
/home/***/public_html/prestashop/img/p/3
/home/***/public_html/prestashop/img/p
/home/***/public_html/prestashop/img

These are the problem folders. At the first time I think - "May is a problem with the chmod of the files" but when I test with all files chmod permission 755 (after that with 777) - the result was the same.

Answer

donald123 picture donald123 · Jul 23, 2012
<?php
  function rrmdir($dir) {
  if (is_dir($dir)) {
    $objects = scandir($dir);
    foreach ($objects as $object) {
      if ($object != "." && $object != "..") {
        if (filetype($dir."/".$object) == "dir") 
           rrmdir($dir."/".$object); 
        else unlink   ($dir."/".$object);
      }
    }
    reset($objects);
    rmdir($dir);
  }
 }
?>

Try out the above code from php.net

Worked fine for me