可能重复:
提前关闭连接
我希望沿着以下路线完成一些事情:
- 用户请求
foo.html
- 页面启动TCPIP套接字和HTTP会话,echos请求标头信息
- 页面echos文件的内容
- 页面关闭了套接字,用户有了文件,每个人都很高兴,不再进行HTTP事务
- 函数FooBar()被调用。。。添加数字、发送电子邮件、更新数据库或其他不会阻止向用户输出页面的任务
在概念上,我的伪PHP代码可能看起来像:
<?php
//Send content to the user
echo "Hello world!!";
//This terminates the script,
//I simply want to close the
//HTTP part without terminating
exit();
//That only took a few milliseconds
//Send an email to someone
//containing a sum of numbers
//in the Fibonacci sequence
//This task might take minutes to do.
mail(
"foo@example.com",
"Your sum is ready",
fibonacci(100)
);
但是我看不到一个明确的方法来实现这一点,因为exit()终止了脚本,我也看不到任何可以控制HTTP套接字的方法。
我很早就看到了关闭连接,这是一个有趣的答案,但我希望在PHP 5.3中实现这一点,而不需要输出缓冲和刷新。
正如Timbo White在这个问题中回答的那样(与我实际使用的代码非常相似,所以我知道它有效),试试这个:
// buffer all upcoming output
ob_start();
// get the size of the output
$size = ob_get_length();
// send headers to tell the browser to close the connection
header("Content-Length: $size");
header('Connection: close');
// flush all output
ob_end_flush();
ob_flush();
flush();
//now you can do anything down here no matter how long it takes
//because the script appears to have returned to the user.
查看register_shutdown_function
http://php.net/manual/en/function.register-shutdown-function.php