在die()之后运行清理代码


Run clean up code after die()

我正在加快一些生成html的php代码的响应时间。代码的一个问题是,当确定不需要显示一条信息时,它会调用sql从数据库中删除该项。这对用户来说是不可见的,而且在下次加载页面之前,服务器也不会看到,因此不需要在系统知道应该运行sql查询时立即运行。

我想做的是用生成的html将响应返回给用户,然后进行sql查询。我尝试了这个flushob_flush,但页面响应仍然没有加载,直到我调用die。

PHP中有没有在调用die()后运行代码,这样用户就可以获得他们的数据,然后我就可以运行我的数据库清理代码,客户端就不用再等我关闭连接了?

您可以使用register_shutdown_function注册关闭函数:

register_shutdown_function(function () {
    // cleanup stuff
});

或者在旧版本的PHP中:

function myFunc() {
  // cleanup stuff
}
register_shutdown_function("myFunc");
感谢@robbrit和@Luis Siquot。我在看register_shutdown_function,由于Luis的评论,我在阅读该页面上的评论,发现了"When using php-fpm, fastcgi_finish_request() should be used instead of register_shutdown_function() and exit()"

这让我想到了fastcgi_finish_request,上面写着:

"This function flushes all response data to the client and finishes the request. This allows for time consuming tasks to be performed without leaving the connection to the client open."

所以看起来fastcgi_finish_request()是我想要的,而不是register_shutdown_function()

编辑:似乎fastcgi_finish_request()需要另一个库,所以使用:

ob_end_clean();
header("Connection: close");
ignore_user_abort(true); // just to be safe
ob_start();
echo "The client will see this!";
$size = ob_get_length();
header("Content-Length: $size");
//Both of these flush methods must be called, otherwise strange things happen.
ob_end_flush();
flush();
echo "The client will never see this";