1

Possible Duplicate:
How do I recursively delete a directory and its entire contents (files+sub dirs) in PHP?

I need to delete a directory in PHP. There's no built-in way to remove directories with files in them, so I know I'll have to use someone else's script.

I've found, and I think I'll use:

<?php

// simply pass the directory to be deleted to this function

function rrmdir($dir)
{
    if (is_dir($dir)) // ensures that we actually have a directory
    {
        $objects = scandir($dir); // gets all files and folders inside
        foreach ($objects as $object)
        {
            if ($object != '.' && $object != '..')
            {
                if (filetype($dir . '/' . $object) == 'dir')
                {
                    // if we find a directory, do a recursive call
                    rrmdir($dir . '/' . $object);
                }
                else
                {
                    // if we find a file, simply delete it
                    unlink($dir . '/' . $object);
                }
            }
        }
        // the original directory is now empty, so delete it
        rmdir($dir);
    }
}
?>

I can't see anything wrong with it, I'm just a bit nervous about not only deleting files, but entire directories, and recursively at that.

Is there any reason this wouldn't work? Have you used anything different?

Community
  • 1
  • 1
mowwwalker
  • 16,634
  • 25
  • 104
  • 157
  • http://stackoverflow.com/questions/3349753/php-delete-directory-with-files-in-it – Muhammad Zeeshan Aug 19 '11 at 05:50
  • Yeah, I saw that. It doesn't have the check to see if the file is '..' or '.' though. I'm guessing it does something different and doesn't need to, but I want people's verification that I'm not going to be deleting my website – mowwwalker Aug 19 '11 at 05:55
  • Can I please get some sort of yeah or nay for the scripts? – mowwwalker Aug 19 '11 at 05:58
  • 2
    @user828584, my answer to that question linked by Lucanos skips dot files outside of the loop. I'd take that over the code in your question any day. – salathe Aug 19 '11 at 06:39
  • Thanks. If you post that as the answer, I'll accept it. People seem to go for that kind of thing – mowwwalker Aug 19 '11 at 06:41

0 Answers0