PHP try/catch语句在不同的选项卡/相同的浏览器上不起作用


PHP try/catch statement not working on different tabs/same browser

我正在PHP脚本上使用以下代码:

try{
    if(file_exists($dir."pid.txt"))throw new Exception("Process is already running");
}
catch(Exception $e){
    die("Warning: ".$e->getMessage()." in ".$e->getFile()." on line ".$e->getLine());
}
touch($dir."pid.txt");
sleep(20); // Just for a proof of concept

基本上脚本的作用是:

如果文件$dir."pid.txt"(其中$dir包含具有正确权限的目录)已经存在,则终止脚本。如果没有,请创建pid.txt文件并在20秒内休眠。

预期效果是防止此脚本被访问两次。

如果我在一个选项卡中打开脚本,并在20秒内在另一个选项卡上重试,那么第二个选项卡上的脚本不会死。然而,不同浏览器中的不同选项卡确实有效。我一直在尝试Chrome、Firefox和IE,这是最新的稳定发布版本。

我100%确信第一个脚本已经正确创建了文件"pid.txt"。

我怀疑这与try/catch语句有关,因为如果我进行

if(file_exists($dir."pid.txt"))die("The process is already running");

它确实有效。然而,这是许多可能的错误之一,我想将它们分组在try/catch语句中。这就是为什么我不想继续采用最后一种方法。

想法?

除非$dir."pid.txt"不是你想象的那样,否则代码应该可以正常工作。或者你在其他地方犯了错误。如果您想要更有用的答案,请提供更多代码。

正如@Yaniro所指出的,为了使脚本按预期工作并在定义时刷新,不必添加缓存头。最终代码为:

header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Expires: Sat, 26 Jul 1970 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
flush();
try{
    if(file_exists($dir."pid.txt"))throw new Exception("Process is already running");
}
catch(Exception $e){
    die("Warning: ".$e->getMessage()." in ".$e->getFile()." on line ".$e->getLine());
}
touch($dir."pid.txt");
sleep(20); // Just for a proof of concept

如果脚本需要很长时间才能完成,则flush()是必要的(从而阻止脚本的并行执行,这也是代码的目的)。