I have failed to get accurate results from this even with echo, flush(), and other buffer manipulation trickery. The following function detects connection status from the OS netstat(1) in linux, even without echoing anything. You may need to alter the parsing for windows or older versions of netstat. It calls an external command so it consume some resources, use it with care e.g. you can call it every some seconds while waiting for long-poll requests. Not tested with ipv6.
//returns connection status (ESTABLISHED, TIME_WAIT, etc) or NOT_FOUND
function getConnectionStatus() {
$remote_ip = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']);
$remote_port=$_SERVER['REMOTE_PORT'];
$cmd="netstat -tn | fgrep ' $remote_ip:$remote_port '";
$pfp=popen($cmd,"r");
if(!$pfp) {
error_log ("getConnectionStatus: $cmd");
}
$buf = fgets($pfp, 1024);
pclose($pfp);
$buf=preg_replace('!\s+!', ' ', $buf); //remove multiple spaces
$buf=trim($buf);
$buf_r=explode(" ",$buf);
if (count($buf_r)) {
$state=$buf_r[count($buf_r)-1];
return trim($state);
}
return "NOTFOUND";
}
//check for it:
if (getConnectionStatus() != "ESTABLISHED") { ...}