views:

43

answers:

2

so I have a delete.php in folder abc so i call localhost/abc/delete.php . I want to be able to delete abc folder and all its contents from server when I call localhost/abc/delete.php How to do such thing?

A: 

Try something like this:

function deleteDir($dir) {
    if (!is_dir($dir)) return unlink($dir);
    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') continue;
        if (!deleteDir($dir.'/'.$item)) return false;
    }
    return rmdir($dir);
}

$dir = substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos($_SERVER['SCRIPT_FILENAME'], '/'));
deleteDir($dir);
MadJawa
This will most likely not work on a Windows host, as it does not allow a directory or file to be deleted if it's in use. The script will have `$dir` as its working directory, and PHP may keep the delete.php script open while the script's executing. At minimum you might have to `chdir()` away from $dir before trying to remote the directory, and even then the delete.php may keep things locked.
Marc B
Thank you, I don't have a Windows box, so I only tested it on Linux.
MadJawa
+1  A: 

This function deletes a directory with all of it's content. Second parameter is boolean to instruct the function if it should remove the directory or only the content


    function rmdir_r ( $dir, $DeleteMe = TRUE )
    {
        if ( ! $dh = @opendir ( $dir ) ) return;
        while ( false !== ( $obj = readdir ( $dh ) ) )
    {
    if ( $obj == '.' || $obj == '..') continue;
    if ( ! @unlink ( $dir . '/' . $obj ) ) rmdir_r ( $dir . '/' . $obj, true );
        }

    closedir ( $dh );
    if ( $DeleteMe )
        {
            @rmdir ( $dir );
        }
    }
//use like this:

rmdir_r( 'abc' );

aSeptik