染卷不卷'blog

12年站长,AI实践中。互联网 IT行业,工作见闻、技术教程全分享。

php / 程序源码

PHP返回前端后继续执行后台任务

以下代码可以实现在php中立即返回前端结果,然后在后台继续执行耗时比较长的任务,提升前端的响应速度。

<?php
$rs = array('code' => 0, 'msg' => 'ok', 'data' => true);
ob_end_clean();
ob_start();
//-----------------------------------------------------------------------------------
//Windows服务器需要加上这行。
//echo str_repeat(" ",4096);
echo json_encode($rs);//返回结果给ajax
//-----------------------------------------------------------------------------------
// 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');
header("HTTP/1.1 200 OK");
header("Content-Type: application/json;charset=utf-8");
ob_end_flush();
if(ob_get_length())
ob_flush();
flush();
if (function_exists("fastcgi_finish_request")) { // yii或yaf默认不会立即输出,加上此句即可(前提是用的fpm)
fastcgi_finish_request(); // 响应完成, 立即返回到前端,关闭连接
}
 
/******** background process starts here ********/
ignore_user_abort(true);//在关闭连接后,继续运行php脚本
/******** background process ********/
set_time_limit(0); //no time limit,不设置超时时间(根据实际情况使用)
/******** Rest of your code starts here ********/
//继续运行的代码
echo '我是不会被输出的!!但是后端操作会继续';
file_put_contents('1.txt',time());
sleep(30);//延迟30
file_put_contents('2.txt','关闭网页30s后创建此文件'.time());

实测后面的echo内容并不会被输出,但是1.txt这个文件确实已经被创建。并且在浏览器网页关闭后30s成功创建2.txt成功!

染卷

本站文章也会定期同步到微信公众号,可以关注下避免错过~

建站 12年 1天
微信公众号

发表评论

邮箱不会公开,带 * 为必填。