以下代码可以实现在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 connectionheader("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);//延迟30file_put_contents('2.txt','关闭网页30s后创建此文件'.time());
实测后面的echo内容并不会被输出,但是1.txt这个文件确实已经被创建。并且在浏览器网页关闭后30s成功创建2.txt成功!
发表评论