简体   繁体   English

在PHP中取消链接文件和目录

[英]Unlinking files and directories in PHP

The following code successfully removes sub directories and the files within them. 以下代码成功删除了子目录及其中的文件。

However it also removes all files in the directory above what is specified as $dir. 但是,它还会删除目录中指定为$ dir以上的所有文件。 This is not desired. 这是不希望的。

Can anybody see what is wrong with the code? 有人可以看到代码有什么问题吗?

    private function unlinkPubDirectory() 
    {
        $dir = DIR_DOWNLOAD_PUB;
        $h1 = opendir($dir);
        while ($subdir = readdir($h1)) {
            $h2 = opendir($dir . $subdir);
            while ($file = readdir($h2)) {
                @unlink($dir . $subdir . '/' . $file);
            }
            closedir($h2); 
            @rmdir($dir . $subdir);
        }
        closedir($h1);
    }

As marked in the comments you should check for '..' as a possible file/directory and omit it. 如注释中所标记,您应检查“ ..”是否为可能的文件/目录,并忽略它。 Additionally, check for errors without the '@'-sign. 此外,检查没有'@'符号的错误。

private function unlinkPubDirectory() 
{
    $dir = DIR_DOWNLOAD_PUB;
    $h1 = opendir($dir);
    while ($subdir = readdir($h1)) {
        if ($subdir == '..') continue; // don't do anything with '..'
        $h2 = opendir($dir . $subdir);
        while ($file = readdir($h2)) {
            unlink($dir . $subdir . '/' . $file);
        }
        closedir($h2); 
        rmdir($dir . $subdir);
    }
    closedir($h1);
}

This will show you what is being deleted 这将向您显示正在删除的内容

while ($subdir = readdir($h1)) {
    $h2 = opendir($dir . $subdir);
    while ($file = readdir($h2)) {
        echo "<p>will remove file " . ($dir . $subdir . '/' . $file);
        }
    closedir($h2); 
    echo  "<p>will remove dir " . ($dir . $subdir);
}

HINT: check for . 提示:检查。 or .. folders and ignore them 或..文件夹并忽略它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM