文件在函数中间消失

Files disappearing in the middle of a function

我今天 运行 遇到的一个有趣的问题,所以我写这个 post 是为了获得有关现在和将来如何处理我应用程序其他部分的建议(也许帮助别人)。

考虑这个方法:

protected function unlinkCachePath($cachePath) {
    if (!file_exists($cachePath)) {
        throw new \Exception("Invalid cache file path '$cachePath'");
    }
    if (!is_writable($cachePath)) {
        throw new \Exception("Check permissions for file path '$cachePath'");
    }
    $result = unlink($cachePath); // delete file
    if (!$result) {
        throw new \Exception("Problem deleting cache file '$cachePath'");
    }
    return true;
}

很简单,对吧?好吧,事实证明 unlink() 函数 间歇性地 无法正常工作。这很奇怪,因为我在尝试 unlink().

之前进行了 file_exists() 检查

但是,它仍然产生 'file not found' 错误。所以我出去调试,看看到底发生了什么。

调试尝试:

protected function unlinkCachePath($cachePath) {

    // debug the cache path
    echo "testing cache path: $cachePath <br />";

    // check if the file exists
    $this->debugFileExists($cachePath,'1'); 

    if (!file_exists($cachePath)) {
       throw new \Exception("Invalid cache file path '$cachePath'");
    }

    // ...check again
    $this->debugFileExists($cachePath,'2'); 

    if (!is_writable($cachePath)) {
       throw new \Exception("Check permissions for file path '$cachePath'");
    }

    // ...and again
    $this->debugFileExists($cachePath,'3'); 

    $result = unlink($cachePath); // delete file

    // ...and again
    $this->debugFileExists($cachePath,'4');

    if (!$result) {
        throw new \Exception("Problem deleting cache file '$cachePath'");
    }
    return true;
}

private function debugFileExists($filePath, $attemptNumber) {
    if (file_exists($filePath)) {
        $response = "pass";
    } else { 
        $response = "fail";
    }
    echo "file_exists() test $attemptNumber: $response <br />";
}

结果:

testing cache path: /path/to/file.json
file_exists() test 1: pass
file_exists() test 2: pass
file_exists() test 3: fail
# unlink(file): No such file or directory
file_exists() test 4: fail

等等,什么?

我在这里,挠头。文件怎么可能存在,然后在同一个函数中,突然不存在了?对到底会发生什么有任何见解吗?

谢谢。

事实证明,我的应用程序的 API 后端是 PHP,而前端是 angular。在极少数情况下,对 API 的多个前端调用会同时发生 - 并且 在函数 中间,文件会删除!由于这个特殊的问题,这个问题没有被广泛的测试发现。