递归删除目录

时间:2014-04-01 11:57:11

标签: php recursion

我在PHP中编写了一个自定义删除函数。函数调用是递归使用的,但在调用函数时,我得到一个错误输出:

// custom delete directory function
function deleteDirectory($dir) {
    if (!file_exists($dir)) return true;
    if (!is_dir($dir) || is_link($dir)) return unlink($dir);
    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') continue;

        // THIS IS LINE 32 LIKE MENTIONED IN THE ERROR
        if (!$this->deleteDirectory($dir . "/" . $item)) {

             // THIS IS LINE 33 LIKE MENTIONED IN THE ERROR
            chmod($dir . "/" . $item, 0777);
            if (!$this->deleteDirectory($dir . "/" . $item)) return false;
        };
    }

    // THIS IS LINE 37 LIKE MENTIONED IN THE ERROR
    return rmdir($dir);
}

function cleanup() {
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->workFolder), RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($files as $name => $fileObject) {
        if (is_file($name)) {
            unlink($name);
        } else if (is_dir($name)) {
            system("/bin/chmod -R 0777 $name");
            $this->deleteDirectory($name);
        }
    }
    $this->deleteDirectory($this->workFolder);
}

我尝试使用" $ this-> deleteDirectory()" 但现在我收到了一个完全不同的错误:

Warning: rmdir(/tmp/533aab0362830/.) [function.rmdir]: Invalid argument in /usr/www/users/kontug/api.medifaktor.de/webservice/passkit/class/Pass.php on line 37

Warning: rmdir(/tmp/533aab0362830/../.ICE-unix) [function.rmdir]: Operation not permitted in /usr/www/users/kontug/api.medifaktor.de/webservice/passkit/class/Pass.php on line 37

Warning: chmod() [function.chmod]: Operation not permitted in /usr/www/users/kontug/api.medifaktor.de/webservice/passkit/class/Pass.php on line 33

Warning: rmdir(/tmp/533aab0362830/../.ICE-unix) [function.rmdir]: Operation not permitted in /usr/www/users/kontug/api.medifaktor.de/webservice/passkit/class/Pass.php on line 37

2 个答案:

答案 0 :(得分:2)

如果函数属于某个类,则应该像这样调用它

$this->deleteDirectory($dir . "/" . $item)

而不是

deleteDirectory($dir . "/" . $item)

答案 1 :(得分:1)

使用课程时,必须将方法称为$this->methodName() 下面是剪辑,对我有用。
你可以试试这个。如果它给出了权限错误,那么您可以添加 chmod 功能 请记住,如果您没有读取权限,则无法遍历目录。所以先设置权限。

   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 (!$this->deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) return false;
        }
        return rmdir($dir);
    }