By calling connection_aborted()
you can find out if the client is still connected or not. This could be done within your for
loop like below.
Also you will need to tell PHP to continue execution after the client disconnects by calling ignore_user_abort()
. If you don't do that, your script will terminate as soon as the client disconnects. Depending on your PHP config, you may also need to set a larger or unlimited time limit using set_time_limit()
.
ignore_user_abort(true);
for ($i = 0; $i < 10000; $i++) {
if(connection_aborted()){
// client disconnected, write to file here
}
echo "string";
ob_flush();
flush();
sleep(2);
}