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

cYr*_*rus 6 php termination

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

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

根据这个,我意外.另外这个例子似乎并没有工作.

而使用非零参数的set_time_limit什么都不做.

我想澄清一下.

Pau*_*xon 9

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

当运行PHP作为命令行脚本,并且脚本的tty消失而脚本没有被终止时,脚本将在下次尝试写入任何内容时死亡,除非将值设置为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 );
}
Run Code Online (Sandbox Code Playgroud)

这证明了触发中止的原因.如果你有一个很容易进入无限循环而没有输出的脚本,你可以使用connection_aborted()来测试连接是否仍然是打开的.