PHP script does not exit the browser

Why does this dummy script continue to execute the event if the client closes the browser (so that the connection to the server)?

  while (true)
 {
     sleep (1);
     file_put_contents ('/ tmp / foo', "I'm alive" .getmypid (). "\ n", FILE_APPEND);
 }

It is unexpected for me in accordance with this . Also this example does not work.

And set_time_limit with a nonzero parameter just does nothing.

I would like some clarification.

+6
source share
2 answers

If you try to write some output to the browser in this loop, you should find the script termination if the connection was interrupted. This behavior is outlined in the documentation for ignore_user_abort

When starting PHP as a command line, the script and script tty goes without completing the script, then the script will die the next time it will try to write something if the value is not set to TRUE

I tried several experiments myself and found that even if you try to execute any output in the browser, the script will continue to work if the output buffer is not already full. If you disable output buffering, the script will abort when you try to exit. This makes sense - the SAPI layer should notice that the request was aborted when it tries to transmit the output.

Here is an example ...

//ensure we're not ignoring aborts.. ignore_user_abort(false); //find out how big the output buffer is $buffersize=max(1, ini_get('output_buffering')); while (true) { sleep( 1 ); //ensure we fill the output buffer - if the user has aborted, then the script //will get aborted here echo str_repeat('*', $buffersize)."\n"; file_put_contents( '/tmp/foo' , "I'm alive ".getmypid()."\n" , FILE_APPEND ); } 

This shows what causes the interrupt. If you had a script that was subject to an infinite loop without output, you can use connection_aborted () to check if the connection is still open.

+9
source

set_time_limit limits the time spent on PHP code. Most of the time (I think> 99.9%) in your program is spent on system calls, writing data to a file and sleeping.

ignore_user_abort cancels only when you write something to the client (not in the local file) - there it is simply impossible to distinguish between an unused and terminated connection otherwise in TCP, unless the client terminates the connection with the RST packet.

+1
source

Source: https://habr.com/ru/post/892788/


All Articles