tags:

views:

370

answers:

2

Has anyone had any experience with deleting the __MACOSX folder with PHP?

The folder was generated after I unzipped an archive, but I can't seem to do delete it.

The is_dir function returns false on the file, making the recursive delete scripts fail (because inside the archive is the 'temp' files) so the directory isn't empty.

Any ideas would be great :)


EDIT:

I'm using the builtin ZipArchive class (extractTo method) in PHP5.

The rmdir script I'm using is one I found on php.net (and have seen on stackoverflow):

<?php
// ensure $dir ends with a slash
function delTree($dir) {
    $files = glob( $dir . '*', GLOB_MARK );
    foreach( $files as $file ){
        if( substr( $file, -1 ) == '/' )
            delTree( $file );
        else
            unlink( $file );
    }
    rmdir( $dir );
}
?>
A: 

Which OS and version are you using?


You need to correct the paths to the directory and files.

// ensure $dir ends with a slash
function delTree($dir) {

    foreach( $files as $file ){
        if( substr( $file, -1 ) == '/' )
            delTree( $dir.$file );
        else
            unlink( $dir.$file );
    }
    rmdir( $dir );
}
bucabay
Using MAC 10.5.8.The server (which I'm deleting the files off) is using Ubuntu linux
brendo
Did you unzip the file from the shell? Or with PHP? What are the permissions on the folder? ie: `ls -l`
bucabay
Could you post your PHP code, it may be an error you do not see.
bucabay
I've updated the original post with these details :)
brendo
+1  A: 

I found an improved version of the function on http://www.php.net/rmdir that requires PHP5.

  1. This function uses DIRECTORY_SEPARATOR instead of '/'.
    PHP defines DIRECTORY_SEPARATOR as the proper character for the running OS ('/' or '\').
  2. The Directory Location doesn't need to end with a slash.
  3. The function returns true or false on completion.
function deleteDirectory($dir) {
    if (!file_exists($dir)) return true;
    if (!is_dir($dir)) return unlink($dir);
    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') continue;
        if (!deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) return false;
    }
    return rmdir($dir);
}
ufk