Source Rally PHP Community Scripts .. Sign up .. Login
A class to do recursive directory actions.
Only works on PHP5
Access: Public      Tags: PHP5, rmdir, scandir, recursion
Add to favourites       Subscribe comments       Copy code       Bookmark
<?php
/*
//remove directory recursively
directoryUtility::remove($dirname);

//scan directory recursively
$dir = directoryUtility::scan($dirname));
print_r($dir);
*/
class directoryUtility
{
    function 
scan($dirname)
    {
        
$array = array();
        
$dir = new RecursiveDirectoryIterator($dirname);
        foreach(
$dir as $k => $v)
        {
            if(!
$dir->isDot())
            {
                
$array[]=$v->getPathname();
            }
            if(
$v->isDir())
            {
                
$subArray directoryUtility::scan($v->getPathname());
                
$array array_merge($array,$subArray);
            }
        }
        return 
$array;
    }
    
    function 
remove($dirname)
    {
        if(
is_dir($dirname))
        {
            
$dir = new RecursiveDirectoryIterator($dirname);
            foreach(
$dir as $k => $v)
            {
                if(!
$dir->isDot())
                {
                    if(
$v->isDir()&&$v->hasChildren())
                    {
                        
directoryUtility::remove($v->getPathname());
                    }
                    else
                    {
                        
unlink($v->getPathname());
                    }
                }
            }
            unset(
$dir);
            
rmdir($dirname);
            return 
true;
        }
        return 
false;
    }
}
?>
Add to favourites       Subscribe comments       Copy code       Bookmark
Sign up to add your own comment here!

Comments

selfsimilar - 15-01-2010 21:54
Add to friends       Mail user
The method 'remove' doesn't work. One issue I found is the line:
if($v->isDir()&&$v->hasChildren())
The variable $v is of class SplFileInfo which doesn't have a 'hasChildren' method.

I removed the hasChildren() test and the code now appears to work properly. The replacement line now reads:
if($v->isDir())
More comments: 1
Shared by:

regin

Mail user Add to friends
All user contributed content is available under the unless specified otherwise.
Remaining copyrights Regin Gaarsmand 2006-2008
About www.SourceRally.net