文件在函数

时间:2016-04-15 21:31:37

标签: php web-services api caching unlink

我今天遇到的有趣问题,所以我写了这篇文章,以获取有关如何在现在以及将来与我的应用程序的其他部分一起处理此问题的建议(也许可以帮助其他人)。

请考虑以下方法:

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()函数间歇地无法正常工作。这很奇怪,因为我在尝试file_exists()之前进行了unlink()检查。

但是,它仍然会生成一个未找到的文件'错误。所以我出去调试,看看到底发生了什么。

调试尝试:

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

等等,什么?

我在这里,挠挠脑袋。文件如何存在,然后在同一个函数中,突然不存在?对于可能发生的事情的任何见解?

谢谢。

1 个答案:

答案 0 :(得分:0)

Turns out, my application's API backend is PHP, while the frontend is angular. In rare cases, multiple frontend calls to an API, which hits unlinkCachePath($cachePath), would happen simultaneously -- and in the middle of a function, the file would delete! Because of this particular problem, the issue was not caught by extensive testing.