Reputation: 1501
I have a PHP script that does this:
$sec = 1;
$id = 1;
while ($sec<20) {
sleep(1);
mysql_query("update test set sec = $sec where id = $id");
$sec++;
}
Whenever I load the script in my browser, it will keep on going even if I closed the browser window after 5 seconds. How can I change this so when the browser window is closed, the script will exit?
Upvotes: 4
Views: 2104
Reputation: 874
PHP connection_aborted() Does not always works
TCP requires that ALL sent packets be acknowledged by the client and therefore the server should detect this as a send timeout at the very least...
session_write_close();//to make flush work
while (connection_status() !== 0) {//this will work if the connection is properly shutdown
//or if it is simply disconnected...
sleep(1);
echo "whatever";
ob_flush();
flush();
}
Upvotes: 0
Reputation: 48367
An awful lot depends on what information the webserver will pass back to the PHP interpreter - even running as a CLI, PHP may only detect the client has aborted when it tries to write to its pty.
In some cases, the webserver may send a signal to the interpreter. But there is no reliable way from PHP to detect if the HTTP connection really has been aborted.
But goven the complications inherent in maintaining long connections over HTTP, it rather begs the question of why you want to create a scenario where this occurs normally.
Upvotes: 1
Reputation: 1773
the ignore_user_abort function sets whether a client disconnect should abort script execution or not. You need to add this in the beginnig of your script
ignore_user_abort(false);
Upvotes: 1
Reputation:
The PHP script is runs in a process on your web server. Simply closing the browser does not necessarily terminate this process. This means that your script may continue to execute, even if the browser connection is closed.
It can be configured not to do this however...
look at the function
ignore_user_abort();
putting this at the top of your script should stop it from running after the user closes the browser
ignore_user_abort(false);
Upvotes: 0
Reputation: 3024
You can use a session variable that destroys when you close the browser and if that is not anymore set you can break the operation.
Upvotes: 0
Reputation: 101513
You can't. Once the HTTP request has been sent off to the server, the PHP script will continue to execute to it's end even if the client has disconnected.
There might be some cases where a script will exit while printing things, but seeing as you're not printing anything it won't exit.
Upvotes: 5