1. 程式人生 > >長時間執行的PHP程式解決方案

長時間執行的PHP程式解決方案

描述:有時候,PHP程式會面臨AJAX過來的呼叫,但邏輯處理的執行又比較漫長,如外部呼叫svn checkout某個專案,那麼就會導致幾個問題:客戶端超時,返回資料集超大,伺服器端指令碼超時,記憶體佔用巨大等 比較了幾個解決方案,以下這個能比較好地解決上述問題,對伺服器的調整也不會造成太大影響。 偽daemon程式,原理:主php程式執行,並不等結果完成就直接返回,中斷與瀏覽器連線,但是斷開後仍能保持執行狀態,執行過程中建立log檔案以備查詢,相當於一個daemon。瀏覽器端的ajax可設時間輪詢執行狀態,輪詢程式查詢log檔案並返回結果; 步驟: 1. 設定.htaccess,確保返回的Content-Type encoding不是gzip

<IfModule mod_env.c>
SetEnvIfNoCase Request_URI "\.php$" no-gzip dont-vary
</IfModule>

2.設定中斷返回以及長時間執行設定
set_time_limit
(0);
ignore_user_abort
(true);// buffer all upcoming output - make sure we care about compression: if(!ob_start("ob_gzhandler"))
    ob_start
();        
echo $stringToOutput
;// 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
();// close current session if(session_id()) session_write_close();//close connection// here, do what you want.