Ahmed Yusuf
Ahmed Yusuf

Reputation: 171

What happens if user aborted by php process exiting browser in the middle?

While PHP Settings of ignore_user_abort is set to False by default, Assuming i have the following code:

1  1ms   $user->giveMoney(500) 
2  2ms   $user->sendNotification("You got 500")
3  1ms   $user->takeCoins(200)

What if the user aborted the browser after exactly 3ms ? would line 3 be executed?

Upvotes: 1

Views: 583

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76413

Yes, it will, seeing as the code you've posted doesn't seem to be producing any output, and you're asking about the behavior in a client-server context. As mentioned in the docs:

When running PHP as a command line script, and the script's tty goes away without the script being terminated then the script will die the next time it tries to write anything, unless value is set to TRUE

I've highlighted some key words: this setting deals with PHP when it's being used for command line scripts. You mention a client, closing his/her browser. There's no TTY, so this setting can be false or true, it won't change a thing.

In your case, though, the man states that:

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

That is to say: the script will keep on running until actual output is really sent to the client. Only then can PHP determine whether or not the connection to the client is still alive. If it isn't then your script will halt.

So unless there is some actual output being sent in that second line of code, and any output buffers are flushed, then yes, the third line will execute. If output is sent, then the script will probably halt.
But if you really want to prevent that third statement from being executed in case of a lost connection, then perhaps call connection_aborted after the second method returns:

$user->sendNotification("You got 500");
if (connection_aborted())
    exit(0);//no error code, just exit
$user->takeCoins(200);

Upvotes: 1

ItalyPaleAle
ItalyPaleAle

Reputation: 7316

You can control that behaviour with http://php.net/manual/en/misc.configuration.php#ini.ignore-user-abort

At the configuration level (e.g. on a .htaccess file) you can set the flag:

php_flag ignore_user_abort 1

At the script level (valid for that script only) you can call this function:

ignore_user_abort(1)

NOTE: The documentation is a bit misleading. ignore_user_abort works ALSO on the server. See also this page for more references.

Upvotes: 1

Related Questions