今天遇到个问题,php怎样去检测客户端是否已经断开连接呢?
开始的时候以为就用函数connection_aborted()或者connection_status()函数就可以知道了,
谁知道坑爹的没反应.
后来通过测试和google找到了方法
其实关键其实就在flush函数,因为php没有通过刷新缓冲区和使用flush()的时候是整个文件输出到客户端内容的.
当输出到客户端的时候实际上php已经运行完了.
所以当使用flush()函数时候,php会马上将输出的内容发送到客户端,但假如客户端已经中断连接的话,服务器就会知道客户端已经中止连接了.
表达能力不是很好,有些错或者看不懂的可以告诉我,谢谢
下面是测试代码:
ob_start();ignore_user_abort(TRUE);//允许php忽略用客户端中断$fp = fopen('connection_test.txt','w+');fwrite($fp, "start run\r\n");for($i=0, $counter=10;$i<$counter;$i++){ if(connection_aborted()){ //提示如果客户端断开连接则在文件里输入提示并停止脚本 fwrite($fp, "user aborted the connection, connection_status return ".connection_status()."\r\nend run\r\n"); exit; }else{ //输出并记录当前状态 fwrite($fp, $i." ".connection_status()." ".connection_aborted()." ".time()."\r\n"); echo $i." ".connection_status()." ".connection_aborted()." ".time()."\r\n"; //下面是刷新php缓冲区,并马上向客户端发送缓冲区内容 ob_flush();//刷新php缓冲区 flush();//所有输出发送到用户的浏览器 ob_end_flush(); } sleep(2);//ZZZzzzz.....}ob_end_clean();fwrite($fp, "end run\r\n");fclose($fp);