0

Below is my controller. Why the controller keeps running even I close the browser after I visited /test? is it normal behavior? I am not using any configuration like ignore_user_abort?

Why this controller keeps outputting log even after I closed my browser?

    /**
     * @Route("/test")
     */
    public function testAction() {

        $logger = $this->get('exception.logger');

        for ($i = 0; $i < 100; $i++) {
            $logger->info("[{$i}] ------------------------------- ");

            sleep(1);
        }

        $response = new StreamedResponse(function() use($logger) {

            for ($i = 0; $i < 100; $i++) {
                $logger->info("[{$i}] ******************************************* ");

                sleep(1);
            }
        });


        $filename = "test.csv";

        $response->headers->set('Content-Type', 'application/force-download');
        $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');

        return $response;
    } 
pmoubed
  • 3,842
  • 10
  • 37
  • 60
  • 1
    it's a server side code, even if your close your browser ( client side) the server continue executing the request – CodeIsLife Oct 10 '17 at 19:24
  • 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(). – CodeIsLife Oct 10 '17 at 20:15

1 Answers1

2

PHP code is server side. The web server logging will continue on the server regardless of whether you close your browser or not. This is normal behavior. See this stackoverflow question for a better explanation: Can closing the browser terminate the PHP script on the server?

turtlechief
  • 100
  • 1
  • 7
  • then what's the use of ignore_user_abort? – pmoubed Oct 10 '17 at 19:33
  • 1
    if your php script tries to output something (to the browser) it will notice that there is no longer a connection. `ignore_user_abort` will tell the php script to keep running anyway (it would normally stop once it notices that your have closed your browser, but it will not notice until it tries to send some type of output to your browser). – turtlechief Oct 10 '17 at 19:40
  • How would detect in the example controller if it was disconnected? – pmoubed Oct 10 '17 at 19:53
  • I am not sure what exactly you are trying to accomplish, but my advice would be to try to find an approach that is not dependent on checking if the browser closed, because it will take a while for your server to realize that the connection was lost. There is almost always more than one way to skin a cat.... take a break to clear your mind and then approach the problem from a different angle. I don't know of a reliable way to immediately know when the connection is lost. – turtlechief Oct 10 '17 at 21:09