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

e_i*_*_pi 7 php directory php-5.4

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

PHP Warning:  mkdir(): File exists in {{{file_path_name_redacted}}} on line 7
Run Code Online (Sandbox Code Playgroud)

查看第 6-8 行,我们可以得到:

if(!is_dir($storeFolder)){
    mkdir($storeFolder, 0644, TRUE);
}
Run Code Online (Sandbox Code Playgroud)

鉴于此文件可能会被多个 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
Run Code Online (Sandbox Code Playgroud)

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

Hug*_*s D 8

Php 检查确认存在竞争条件,并建议编写代码的最安全方法是:

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

更多解释\xc2\xa0 (编辑:链接已失效,请参阅上面的链接)

\n

这感觉很奇怪,但确实有效。祝你好运。

\n