关闭连接后继续处理 [英] Continue processing after closing connection

查看:81
本文介绍了关闭连接后继续处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP中是否有一种方法可以关闭连接(本质上是告诉浏览器,没有更多数据可发送),而是继续进行处理.我正在考虑的特定情况是,我想提供缓存的数据,然后,如果缓存已过期,我仍然会提供缓存的数据以快速响应,关闭连接,但继续进行处理以重新生成并缓存新的数据数据.本质上,唯一的目的是使网站显得更具响应性,因为在用户等待内容重新生成时不会偶尔出现延迟.

Is there a way in PHP to close the connection (essentially tell a browser than there's no more data to come) but continue processing. The specific circumstance I'm thinking of is that I would want to serve up cached data, then if the cache had expired, I would still serve the cached data for a fast response, close the connection, but continue processing to regenerate and cache new data. Essentially the only purpose is to make a site appear more responsive as there wouldn't be the occasional delay while a user waits for content to be regenerated.

更新:

PLuS与我一直在寻找最接近的答案.为了澄清几个问题,我正在寻找可以实现以下步骤的东西:

PLuS has the closest answer to what I was looking for. To clarify for a couple of people I'm looking for something that enables the following steps:

  1. 用户请求页面
  2. 连接打开到服务器
  3. PHP检查缓存是否已过期(如果仍然有效),则提供缓存并关闭连接(在此结束).如果已过期,请继续执行4.
  4. 服务过期的缓存
  5. 关闭连接,以便浏览器知道它不在等待更多数据.
  6. PHP重新生成新数据并将其缓存.
  7. PHP关闭.

更新:

这很重要,它必须是纯PHP解决方案.无法安装其他软件.

This is important, it must be a purely PHP solution. Installing other software is not an option.

推荐答案

我终于找到了解决方案(感谢Google,我不得不继续尝试不同的搜索字词组合).感谢arr1在此页面上的评论(大约三分之二)在页面的下方).

I finally found a solution (thanks to Google, I just had to keep trying different combinations of search terms). Thanks to the comment from arr1 on this page (it's about two thirds of the way down the page).

<?php
ob_end_clean();
header("Connection: close");
ignore_user_abort(true);
ob_start();
echo 'Text the user will see';
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush(); // All output buffers must be flushed here
flush();        // Force output to client
// Do processing here 
sleep(30);
echo('Text user will never see');

我还没有实际测试过,但是,简而言之,您发送了两个标头:一个标头告诉浏览器确切的数据量,然后一个标头告诉浏览器关闭连接(只有在接收到标头之后才会这样做)预期的内容量).我还没有测试过.

I have yet to actually test this but, in short, you send two headers: one that tells the browser exactly how much data to expect then one to tell the browser to close the connection (which it will only do after receiving the expected amount of content). I haven't tested this yet.

这篇关于关闭连接后继续处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆