die()后运行清理代码

时间:2014-09-12 16:10:59

标签: php die

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

我想要做的是使用生成的html将响应返回给用户,然后进行sql查询。我正在尝试此flushob_flush,但在我打电话给死之前,页面响应仍未加载。

在PHP调用die()后运行代码是否存在,以便用户获取数据然后我可以运行我的数据库清理代码,客户端不再等待我关闭连接?

2 个答案:

答案 0 :(得分:3)

您可以使用register_shutdown_function注册关机功能:

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

或者在旧版本的PHP中:

function myFunc() {
  // cleanup stuff
}

register_shutdown_function("myFunc");

答案 1 :(得分:0)

感谢@robbrit和@Luis Siquot。我正在查看register_shutdown_function,由于路易斯的评论,我正在阅读该页面上的评论,我遇到了"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";