is_dir()是否不可靠,或者是否存在可以在此缓解的竞争条件?

时间:2017-06-02 07:04:27

标签: php directory php-5.4

在工作中,我继承了一个具有文件上传过程的Web应用程序。偶尔的一部分过程(每两周左右一次)会触发以下错误:

PHP Warning:  mkdir(): File exists in {{{file_path_name_redacted}}} on line 7

看第6-8行,给我们:

if(!is_dir($storeFolder)){
    mkdir($storeFolder, 0644, TRUE);
}

鉴于这个文件可以被多个PHP进程击中,我相信竞争条件可能在这里发挥作用。我在过去曾经管理的其他网站上看到了同样的问题,同样在蓝色的月亮中也只发生过一次。

我认为正在发生的是用户双击上传按钮,这导致两个PHP进程几乎完全同时执行,如下所示:

Process 1 executes line 6 - dir does not exist
Process 2 executes line 6 - dir does not exist
Process 1 executes line 7 - directory is created
Process 2 executes line 7 - directory cannot be created as it already exists

这是竞争条件的情况吗,正如我上面所解释的那样(即有其他人注意到这一点),和/或是否有某种方法可以减轻错误,另外还会关闭警告的错误报告?

2 个答案:

答案 0 :(得分:1)

Php检查确认为race condition exists,并建议编写代码的最安全方法是:

if (!is_dir($dir) && !mkdir($dir) && !is_dir($dir)) {
        throw new \RuntimeException(sprintf('Directory "%s" could not be created', $dir));
    }

A bit more of explanation

这感觉很奇怪,但确实可以。祝你好运。

答案 1 :(得分:1)

我看到很多项目都使用了 Hugues D's solution,它似乎工作得很好。但是,在使用 $recursive = true 时它可能会失败,因为 a bug in PHP reported in 2005,他们以某种方式拒绝修复(是的,它一个错误)。

这是迄今为止对我有用的片段:

/**
 * Safer version of mkdir(..., ..., true) without race condition issues
 *
 * @see https://bugs.php.net/bug.php?id=35326
 *
 * @param string $dirname A directory path to create
 * @param int    $mode    Permission
 */
function safeMkdirRecursive(string $dirname, int $mode = 0777): void {
    $current = '';
    foreach (explode(DIRECTORY_SEPARATOR, $dirname) as $part) {
        $current .= $part;
        if ($current !== '' && !@mkdir($current, $mode) && !is_dir($current)) {
            throw new RuntimeException('Failed to create directory: ' . $current);
        }
        $current .= DIRECTORY_SEPARATOR;
    }
}

免责声明:我没有在 Windows 上测试过!