[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

How can I delete a folder along with all subfolders and contained files with PHP

Posted on 2008-06-23
3
Medium Priority
?
1,177 Views
Last Modified: 2012-05-05
HI,

I need a way to remove a folder and all its sub folders and files with php.  

I know i can remove an empty folder with "rmdir", but in this case folder contains 3 subfolders, each of which contain several files, and I want to delete all the contents and the directory.
0
Comment
Question by:Susurrus
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 2

Accepted Solution

by:
minibago earned 2000 total points
ID: 21849097
I 'borrowed' this for you (I left in the originators details so you can thank him if you want though) from php.net document comments for rmdir().

This function builds on the suggestion by davedx, but doesn't keep going on failure.  It also doesn't remove dot-files, since those usually should be deleted explicitly.

Hope that helps you =)
Isaac Z dot Schlueter i at foohack dot com
 
<?php
/**
 * rm_recurse
 * @description Remove recursively. (Like `rm -r`)
 * @see Comment by davedx at gmail dot com on { http://us2.php.net/manual/en/function.rmdir.php }
 * @param file {String} The file or folder to be deleted.
 **/
function rm_recurse($file) {
    if (is_dir($file) && !is_link($file)) {
        foreach(glob($file.'/*') as $sf) {
            if ( !rm_recurse($sf) ) {
                error_log("Failed to remove $sf\n");
                return false;
            }
        }
        return rmdir($file);
    } else {
        return unlink($file);
    }
}
?>

Open in new window

0
 
LVL 6

Expert Comment

by:ixti
ID: 21849213
rmdir cannot delete non-empty dir, so you have to delete all subfoldera and files first. For example you can do it with function from code snippet. For more details, please check out http://ru2.php.net/rmdir
<?php
    // dan's comment (http://ru2.php.net/manual/ru/function.rmdir.php#81692)
    function remove_dir($dir)
    {
        if(is_dir($dir))
        {
            $dir = (substr($dir, -1) != "/")? $dir."/":$dir;
            $openDir = opendir($dir);
            while($file = readdir($openDir))
            {
                if(!in_array($file, array(".", "..")))
                {
                    if(!is_dir($dir.$file))
                        @unlink($dir.$file);
                    else
                        remove_dir($dir.$file);
                }
            }
            closedir($openDir);
            @rmdir($dir);
        }
    }
?>
 
// So now you can delete dir with:
 
<?php remove_dir('/path/to/dir/which/has/to/be/deleted');

Open in new window

0
 
LVL 6

Expert Comment

by:ixti
ID: 21849233
If minibago's solution will not work, try another (from php.net's):

<?php
function rm_recursive($filepath)
{
    if (is_dir($filepath) && !is_link($filepath))
    {
        if ($dh = opendir($filepath))
        {
            while (($sf = readdir($dh)) !== false)
            {
                if ($sf == '.' || $sf == '..')
                {
                    continue;
                }
                if (!rm_recursive($filepath.'/'.$sf))
                {
                    throw new Exception($filepath.'/'.$sf.' could not be deleted.');
                }
            }
            closedir($dh);
        }
        return rmdir($filepath);
    }
    return unlink($filepath);
}
?>

Open in new window

0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

649 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question