Vivek
Vivek

Reputation: 85

What happens to a killed HTTP request?

If I make a request to the server from my browser and before it serves me the page, I kill the request(meaning I close the tab), does the request still gets executed on the server side? Or does the server abort the execution process too? Is this different from how PHP handles this?

Is the Connection: Keep-Alive header related to this and makes any difference?

Upvotes: 1

Views: 481

Answers (1)

Vivek
Vivek

Reputation: 85

Ok once the request is made from the browser to the server, the server will execute the script entirely by default. ignore_user_abort doesn't seem to make any difference and quoting the below from their notes section.

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().

Below script works just fine even if you close the browser or browser tab.

<?php

sleep(10);

file_put_contents("test.txt", "I am still alive dude!!");

Connection: Keep-Alive is to just to keep the connection between server and client browser alive. As mentioned in the comments, it is only to reuse the connection for further requests because apparently establishing a IP connection is a "heavy" task. This has nothing to do with whether to stop script execution on the server or not.

As said in the docs, you can use it as below:

HTTP/1.1 200 OK
Connection: Keep-Alive
Keep-Alive: timeout=5, max=1000

where timeout is the time in seconds where the server allows a connection with the client to remain idle and max is the maximum requests that can be sent on this connection before closing it.


Conclusion: All in all, there is no real way to dynamically decide if connection is closed by the client or not(at least in PHP), apart from cheap hacks like output buffering and some test headers etc before performing tedious resource heavy tasks(but that would simply convolute the code base).

Upvotes: 1

Related Questions