【问题标题】:Run clean up code after die()在 die() 之后运行清理代码
【发布时间】:2014-11-06 21:09:28
【问题描述】:

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

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

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

【问题讨论】:

  • 你应该完全忘记这一点,而是调查为什么在information does not need to be displayed时必须删除数据库的行
  • @Sebas 因为这个工具从 7 个不同的(只读的)数据库中提取,并将所有信息编译到一个页面上。它有自己的数据排序条目,不会影响原始数据数据库。因此,如果从其中一个数据库中删除了数据,我直到下次加载我的页面时才会发现它。因此,当我的页面被加载时,我需要删除不再存在的数据的排序条目。不,我不能编辑改变数据库的代码来改变我的。

标签: php die


【解决方案1】:

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

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

或者在旧版本的 PHP 中:

function myFunc() {
  // cleanup stuff
}

register_shutdown_function("myFunc");

【讨论】:

  • 来自手册:“关闭回调作为请求的一部分执行,因此可以从它们发送输出并访问输出缓冲区。”关闭函数算作请求的一部分,在这种情况下将涉及相同的时间
  • Luis 是对的,虽然函数是在 die 之后调用的,但缓冲区并没有完全刷新,连接保持打开状态,直到关闭回调执行完毕。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-29
    • 2013-12-17
    • 2018-07-21
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多