PHP 返回結果給前端/ajax后,在后臺繼續執行代碼的方法
. 問題背景
在實際項目開發中,遇到一個問題:
前端通過 Ajax 請求后臺 PHP API 接口,執行多文件的打包下載操作,該請求由于需要更新大量的數據(日志、統計等信息)到數據庫且還需要執行較大的磁盤IO操作,導致該請求很耗時間。由于前端頁面的更新需要快速響應,因此需要 PHP 快速返回計算結果,然后后臺繼續執行余下的操作。
2. 解決方法
exit() 之后還能繼續執行代碼的方法有 析構函數 __destruct() 以及 register_shutdown_function() (記日志或者xhprof等性能分析等有一定耗時的代碼),但針對 ajax 請求并不能立即返回
考慮到 HTTP 請求協議中可以通過 flush() 進行局部內容輸出,立即返回請求結果給前端,再將耗時操作繼續執行,即通過該技術解決問題
{ $rs = ['code' => 0, 'msg' => 'ok', 'data' => true]; ob_end_clean(); ob_start(); //----------------------------------------------------------------------------------- //Windows服務器需要加上這行。 //echo str_repeat(" ",4096); echo json_encode($res);//返回結果給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 ********/ //繼續運行的代碼 ... ...
對于長時間運行的代碼可以考慮使用消息隊列方式替代 HTTP 的 flush 特性 — 推薦
后臺異步調用 HTTP 請求的方法可通過 fsockopen 實現
As of August 2012, all browsers seem to show an all-or-nothing approach to buffering. In other words, while php is operating, no content can be shown.
In particular this means that the following workarounds listed further down here are ineffective:
ob_flush (), flush () in any combination with other output buffering functions;
changes to php.ini involving setting output_buffer and/or zlib.output_compression to 0 or Off;
setting Apache variables such as "no-gzip" either through apache_setenv ()or through entries in .htaccess.
So, until browsers begin to show buffered content again, the tips listed here are moot.
————————————————
版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
原文鏈接:https://blog.csdn.net/aoshilang2249/article/details/82772329

浙公網安備 33010602011771號