0

I am trying to remove a directory and all of its contents with this script...

<?php
$app = $_POST['app'];

if (isset($_POST['app'])) {
    $dir = "../apps/" . $app . "/";

function rrmdir($dir) {
    if (is_dir($dir)) {
        $objects = scandir($dir);
        foreach ($objects as $object) {
            if ($object != "." && $object != "..") {
                if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
            }
        }
        reset($objects);
        rmdir($dir);
    }
}
}
?>

The $post is working fine and the script is not returning any errors but its just not deleting the directory. Could it have something to do with folder permissions? Do I need to activate any PHP extensions?

--EDIT-- The linked duplicate does not do what I want and I don't know how to change the code for it. I am deleting a directory on the client side so I can't use __DIR__ as that keeps the path like this /test/app and I need them to be like this \test\app also the code does not remove the folder but it does remove all of the contents. I believe that is to do with the FilesystemIterator::SKIP_DOTS line. I need the code to remove the folder as well because when or if the user installs the app again it wont work due to the duplicate folder.

Working code:

<?php
$app = $_POST['app'];

if (isset($_POST['app'])) {
$dir ="../apps/" . $app;

$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
    $file->isDir() ?  rmdir($file) : unlink($file);
}
rmdir($dir);
}
?>
4

1 回答 1

1

@Gordon 发给我的链接帮助我找到了答案。

这是我的新工作代码。

<?php
$app = $_POST['app'];

if (isset($_POST['app'])) {
$dir ="../apps/" . $app;

$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
    $file->isDir() ?  rmdir($file) : unlink($file);
}
rmdir($dir);
}
?>
于 2013-07-21T22:32:31.703 回答