1

I am trying to remove folders and its files and sub folders using php.

This is how I tried it.

$dir     = "../../images/$category_id/$delId"; 
$it      = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
    if ($file->isDir()){
        rmdir($file->getRealPath());
    } else {
        unlink($file->getRealPath());
    }
}
rmdir($dir);

This is working on php 5.5+, but is doesn't work in php 5.2.17.

Can anybody tell me how I get it to work on 5.2 also. Thank you.

user3733831
  • 2,886
  • 9
  • 36
  • 68
  • is there any error of 5.2! what exactly is the response you get? – Kumar Saurabh Sinha Feb 08 '16 at 14:17
  • @SaurabhSinha, yes there is an error `
    Fatal error: Undefined class constant 'SKIP_DOTS' in /home2/public_html/admin /includes/process_edit.php on line 124
    `
    – user3733831 Feb 08 '16 at 14:19
  • 1
    Here you can definitely find several ways to do that: http://stackoverflow.com/questions/4594180/deleting-all-files-from-a-folder-using-php – nuss Feb 08 '16 at 14:24

1 Answers1

0

Use below code:-

function rrmdir($dir) { 
  foreach(glob($dir . '/*') as $file) { 
    if(is_dir($file)) rrmdir($file); else unlink($file); 
  } rmdir($dir); 
}

You can also simply do it by below statement:-

system('/bin/rm -rf ' . escapeshellarg($dir));

Hope it will help you :)

Ravi Hirani
  • 6,511
  • 1
  • 27
  • 42