Search code examples
phprmdir

PHP Multi Directory delete


So I'm creating an image upload site and I need to delete multiple directories and files simultaneously. I have managed to create code that does the job however I'm unsure whether this is 'good code' as I'm repeating myself.

Is there a better way to write the below?

$dirname = 'uploads/'.$album_id;
$dirnamethumb = 'uploads/thumbs/'.$album_id;

if (is_dir($dirname))
    $dir_handle = opendir($dirname);
if (!$dir_handle)
    return false;
while($file = readdir($dir_handle)) {
    if ($file != "." && $file != "..") {
        if (!is_dir($dirname."/".$file))
            unlink($dirname."/".$file);
        else
            delete_directory($dirname.'/'.$file);
    }
}

if (is_dir($dirnamethumb))
    $dir_handle = opendir($dirnamethumb);
if (!$dir_handle)
    return false;
while($file = readdir($dir_handle)) {
    if ($file != "." && $file != "..") {
        if (!is_dir($dirnamethumb."/".$file))
            unlink($dirnamethumb."/".$file);
        else
            delete_directory($dirnamethumb.'/'.$file);
    }
}
closedir($dir_handle);
rmdir($dirname);
rmdir($dirnamethumb);
return true;

Thank you in advance for your help!


Solution

  • Why not try this recursive function from similar question

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