User Contributed Notes 6 notes

A trick to detecting if a connection is closed without having to send data that will otherwise corrupt the stream of data (like a binary file) you can use a combination of chunking the data on HTTP/1.1 by sending a "0" ("zero") as a leading chunk size without anything else.

*NOTE* it's important to note that it's not a good idea to check the stream more then once every few seconds. By doing this you are potentially increasing the data sent to the user with no gain to the user.

A good reason to do it this way is if you are generating a report that takes a long time to run and takes a lot of server resources. This would allow the server to detect if a user canceled the download and do any cleanup without corrupting the file file being download.

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.

// we will check the communication state when the script finishedregister_shutdown_function(verifyCommunication); echo "blabla";// this sleep is used to have time to break the connection on the client sidesleep(10); echo"tata";?>

I use such a process to cancel a request if the client didn't get the acknowledgement because he will redo his request...

PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Simply using an echo statement does not guarantee that information is sent, see flush().

(connection_aborted not working)I had this problem years ago, now the problem came back after upgrading php... i tried everything i found and in the end the function ob_end_flush(); on top of script as post in php bug track solved the problem. Im using windows 7 x64 / php 5.2.4 / apache 2.2.14 (win32)

try adding ob_end_flush(); on top of you script. i read something about this but can't remember where, it was related to a bug or something.