php判斷頁面是否關閉的方法:可以利用connection_status()函數(shù)來進行判斷。如果該函數(shù)返回0,則表示連接運行正常;如果返回1,則表示連接由用戶或網(wǎng)絡錯誤終止。
相關函數(shù)介紹:
connection_status() 函數(shù)返回當前的連接狀態(tài)。
(推薦教程:php視頻教程)
可返回的可能值:
-
0 – CONNECTION_NORMAL – 連接運行正常
-
1 – CONNECTION_ABORTED – 連接由用戶或網(wǎng)絡錯誤終止
-
2 – CONNECTION_TIMEOUT – 連接超時
-
3 – CONNECTION_ABORTED & CONNECTION_TIMEOUT
代碼實現(xiàn):
echo str_repeat(" ",3000); ignore_user_abort(true); mylog('online'); while (true) { /* * 1、程序正常結束 connection_status 0 * 2、點擊瀏覽器“停止”按鈕 connection_status 1 * 3、超時 connection_status 2 */ echo "test<br>n"; //注意程序一定要有輸出,否則ABORTED狀態(tài)是檢測不到的 flush(); sleep(1); if (connection_status()!=0){ mylog('offline'); die('end the script'); } } function mylog($str) { $fp = fopen('e:/abort.txt', 'a'); $str = date('Y-m-d H:i:s').$str."rn"; fwrite($fp, $str); fclose($fp); }