gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:03:29 24 4
gpt4 key购买 nike

在工作中,我继承了一个具有文件上传过程的 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

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

最佳答案

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

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

关于php - is_dir() 是否不可靠,或者是否存在可以在此处缓解的竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44322783/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com