tags:

views:

202

answers:

4

If I'm generating a stream of data to send out to a browser, and the user closes the browser, can I tell within PHP that I don't need to bother generating or sending the rest of the stream? I'd like to insert something into this loop:

while (!feof($pipes[1])) {
   echo fgets($pipes[1]);
}

My fallback plan is to have the browser use a JavaScript onunload to hit another PHP page to kill the process that's generating the data, but it would be cleaner if PHP could tell when I'm echoing to nowhere.

+10  A: 

By default PHP will abort the script if the user navigates away. There are however times where you don't want this to happen so php has a config you set called ignore_user_abort.
http://php.net/manual/en/misc.configuration.php

Ballsacian1
+1  A: 

There's also a function called register_shutdown_function() that is supposedly executed when execution halts. I've never actually used it, so I won't vouch for how well it works, but I thought I'd mention it for completeness.

Emil H
Close but in this case he just wants to stop processing the data on user abort.
Ballsacian1
+1  A: 

I believe that script will automatically abort when loaded normally (No ajax). But if you want to implement some sort of long polling via php using xmlhttprequest I think you will have to do it with some sort of javascript because then php can't detect it. Also like to know the precise case.

Alfred
A: 

These answers pointed me towards what I was looking for. The underlying process needed special attention to kill it. I needed to jump out of the loop. Thanks again, Stack Overflow.

 while (!feof($pipes[1]) && !connection_aborted())
 {
  echo fgets($pipes[1]);
 }

 if (connection_aborted())
 {
  exec('kill -4 '.$mypid);
 }
Ross Morrissey