Remove a Directory and Its Content with PHP

09 January 2010

The function below deletes directories with many options. You can delete directories recursively, delete only content of directories or remove files in a directory with regular expression. I wrote details in PHPDoc format.

/**
 * removes files in a directory
 * examples:
 * <pre>
 * removeDir('/home/gudubeth/pics');
 *      //delete everything and the directory itself.
 * removeDir('/home/gudubeth/pics', false);
 *      //delete only content of the directory. subdirectories are deleted too.
 * removeDir('/home/gudubeth/pics', false, false);
 *      //delete only content of the directory. subdirectories
 *      //are NOT deleted
 * removeDir('/home/gudubeth/pics', false, true, '/.*\.jpg/');
 *      //delete only jpg files inside this directory and its sub directories.
 * </pre>
 * @param str $dir  directory path
 * @param bool $deleteDir   deletes the directory itself if it is true.
 *                          default is true
 * @param bool $recursive   deletes files recursively if it is true.
 *                          default is true
 * @param str $regEx        deletes files only if they match this $regEx.
 *                          Regular expression checking is done with preg_match.
 *                          default is '/.*/' which means 'everything'
 * @return  bool    true if every file is deleted successfully or there are
 *                  no files found to delete. false if any of the deletions
 *                  is unsuccessful
 *
 * */
function removeDir($dir, $deleteDir=true, $recursive=true, $regEx="/.*/") {
    if(!$dh = @opendir($dir)) return false;
    $result=true;
    while (($file=readdir($dh))!==false) {
        if($file!='.' && $file!='..'){
            if(is_dir( $dir.'/'.$file) && $recursive)
                $result = removeDir($dir.'/'.$file, true, true, $regEx) && $result;
            else if(preg_match($regEx, $file))
                $result = @unlink($dir.'/'.$file) && $result;
        }
    }
    closedir($dh);
    if($deleteDir) $result = @rmdir($dir) && $result;
    return $result;
}

Vote this post

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...
Categories: Coding
Tags: ,

Comments

Leave a Reply