PHP 脚本不会在浏览器退出时退出

标签 php termination

如果客户端关闭浏览器(因此与服务器的连接),为什么这个虚拟脚本会继续运行事件?

while ( true )
{
    sleep( 1 );
    file_put_contents( '/tmp/foo' , "I'm alive ".getmypid()."\n" , FILE_APPEND );
}

根据 this 这对我来说是出乎意料的.还有 this示例似乎不起作用。

set_time_limit使用非零参数什么都不做。

我想要一些说明。

最佳答案

如果您尝试在该循环中向浏览器写入一些输出,您会发现如果连接已终止,脚本将中止。 ignore_user_abort 的文档中暗示了此行为

When running PHP as a command line script, and the script's tty goes away without the script being terminated then the script will die the next time it tries to write anything, unless value is set to TRUE

我自己尝试了一些实验,发现即使您确实尝试了一些浏览器输出,如果输出缓冲区尚未满,脚本也会继续运行。如果关闭输出缓冲,脚本将在尝试输出时中止。这是有道理的 - SAPI 层在尝试传输输出时应该注意到请求已终止。

这是一个例子...

//ensure we're  not ignoring aborts..
ignore_user_abort(false);

//find out how big the output buffer is
$buffersize=max(1, ini_get('output_buffering'));


while (true)
{
    sleep( 1 );

    //ensure we fill the output buffer - if the user has aborted, then the script
    //will get aborted here
    echo str_repeat('*', $buffersize)."\n";

    file_put_contents( '/tmp/foo' , "I'm alive ".getmypid()."\n" , FILE_APPEND );
}

这演示了触发中止的原因。如果您的脚本容易进入无输出的无限循环,您可以使用 connection_aborted()测试连接是否仍然打开。

关于PHP 脚本不会在浏览器退出时退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6698820/

相关文章:

php - 如果结果与数据库条目匹配,则在 php 中刷新 rand()

prolog - 更好地终止 s(X)-sum

c - 如何实现 exit() 函数的模拟? -std=c99

php - 将 javascript 日期和时间对象插入数据库

php - jQuery、PHP - 如何制作 'Get started' 弹出框

php - 更新查询不起作用的问题

javascript - 如何终止 Javascript 执行、退出/死亡/致命断言等?

java - 奇怪的Java问题,while循环终止

ssl - TLS 终止 : reencrypt using a destinationCACertificate

php - mysql 语法错误,看不出什么问题