PHP, Ajax, and the lifespan of the request - php

I was wondering about the lifespan of a PHP script when called via Ajax. Assume that there is a long-running (i.e. 30 seconds) PHP script on a server and that page is loaded via Ajax. Before the script completes, the user closes the browser. Does the script continue running to completion, is it terminated, or is this a function of the server itself (I'm running Apache fwiw). Thanks for any help.

This may be of interest: ignore_user_abort()
ignore_user_abort — Set whether a client disconnect should abort script execution
However note
PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client.

The script will continue running. Closing the browser on the client does not notify the server to stop processing the request.

If you have a large time consuming script, then I would suggest splitting it up into chunks. Much better that way

Related

Will Ajax be aborted after the request is done and the browser is closed?

I am working on the php to generate few files using ajax requests and my doubt is that will the response once sent will not complete all its action if the browser is closed?
When you close your browser or hit the cancel button, the connection to the webserver is terminated. Whether your server-side php script will continue with execution, depends on the PHP/Apache configuration.
Default configuration is to terminate the execution of the PHP script, as soon as the connection is cancelled. However, you can change this default setting to continue execution!
To do this, please use the ignore_user_abort function:
http://php.net/manual/en/function.ignore-user-abort.php
You can read more about the topic here:
http://php.net/manual/en/features.connection-handling.php
There's some more discussion about that here as well:
PHP auto-kill a script if the HTTP request is cancelled/closed
Addition: Just in case, that I am misunderstanding your question: When closing the browser your Javascript code on the client side will of course NOT continue with execution after the PHP script finished.

Does the server "shut down" when the browser is closed? PHP - MYSQL

I was wondering - as I wrote a snippet of code that could update up to 10,000 rows and might take a few seconds to complete, if when the file is accessed via an ajax request, the post query is send to the php file, then the browser is closed, does the file get fully executed? assume it takes about 25 seconds to complete the request, the user might not wait for 25 seconds, is good enough to "ping" this file and let the user browse along or close its browser window as the mysql queries are taking place?
The request has 3 parts
A browser connected to the web server
PHP script that is executed by the server
A query running in the DB server
When you close the browser, connection with the server is closed. The server may or may not kill the started PHP script (if PHP is running as apache module, it would be killed, unless ignore_user_abort is called). Also the web server may have a time limit for the request and either kill the script or just send the client a connection timeout message, without killing the script, but without giving it the chance to send anything to the browser.
Here is the tricky part - the update is running in the database and it won't be killed by the web server, neither by PHP.
So what you want to achieve is pinging a PHP script, that is executing a query, but the client do not wait the result. You may or may not want the query itself to be asyncronous (the PHP script not to wait the query), but you have to tell the client that the request is fulfilled, by sending content-length of 0 for example, and flushing the output (the http headers actually), and running PHP with ignore_user_abort so it continues the execution.
Use ignore-user-abort to continue running the script even after the client has disconnected
ignore_user_abort(true);
set_time_limit(0);
You can use connection_status to track if the connection has disconnected
if (connection_status()!=0) { //connection disconnected
Here's the answer for your question:
http://www.php.net/manual/en/features.connection-handling.php
Normally no, but your script pass in ABORTED status.
More details in the manual page about Connection handling:
http://www.php.net/manual/en/features.connection-handling.php
Internally in PHP a connection status is maintained. There are 3
possible states:
0 - NORMAL
1 - ABORTED
2 - TIMEOUT
When a PHP script is running normally the NORMAL state, is active. If
the remote client disconnects the ABORTED state flag is turned on. A
remote client disconnect is usually caused by the user hitting his
STOP button.
As soon as you close the browser, it disconnects from the server before getting the reply. I do not know exactly how different servers behave in this condition but I assume that most of the server will abort the thread that they are working on to reply the request.
Further, things can be different with different operations - i.e. file i/o or database operation. If it is an atomic database operation, my assumption is, it will complete any how.

Can you tell a php server to abort the execution of a previously running script?

My web page uses an ajax call to return data from a very long php script, so if I exit the page early and reload the page, that php script is still being carried out, which will cause me problems.
Is there a way I could tell the server to abort the execution of the previous ajax request, if there is one that's still running?
thanks
Not directly. You will need to set up a scheme where the work is offloaded to an external (to the web server) process, and that process has a communication channel with the web server set up that enables it to check if it should drop what it's doing every so often (e.g. a simple but not ideal scheme would be checking for the last-modified time of a "lock file"; if it's more than X seconds in the past, abort the task).
Your web page would then make a call to a script that would then "keep alive" the background task appropriately (e.g. by touching the lock file of the previous example).
This way, when the task is initiated through an AJAX request, the client begins making "keep-alive" requests to the server and the server forwards the "keep-alive" message to the external process. If the user reloads the page the "keep-alive" requests stop and the worker process will abort when the keep-alive threshold elapses. If all goes well and the work completes, your server would detect this through the communication channel it has with the worker process and report this back to the client on their next keep-alive "ping".
Maybe try use set_time_limit() function for this script.
Or create some few php scripts and randomly generates a url for it.
did you try setting the XMLHttpRequest object to null when the page reloads?

HttpSendRequest not waiting for PHP script to finish

I'm sending an HTTP POST request from my C++ app to a PHP script on a server. Using HttpOpenRequest/HttpSendRequest/etc. Currently it waits for the PHP script to finish executing before HttpSendRequest returns. Is there anyway to change this functionality?
I'm sending the data just before my C++ application closes, so I don't want it to sit there for 10+ seconds waiting for the PHP script to finish executing. I just want it to send the data, then close the app.
One thing I was thinking was to have the PHP script spawn another PHP script in a different process using the exec command, so the first script would return straight away. However, I'm sending a lot of data with my HTTP POST request, so would need it pass this data to the spawned process.
Ideally I just want a flag to set to tell HttpSendRequest not to wait. I couldn't see anything obvious in the docs, but may have missed something.
You can call InternetOpen with the INTERNET_FLAG_ASYNC and have your callback do nothing of consequence.
Here's some example code to get you started:
http://www.codeproject.com/KB/IP/asyncwininet.aspx
Then (as rik suggests), call ignore_user_abort(true); at the top of your PHP script to ensure it executes fully.
ignore_user_abort
You may want to ignore_user_abort() in your PHP script. Then you can close the connection from your C client after the data is sent and PHP will continue to do whatever it's supposed to do.

Does php execution stop after a user leaves the page?

I want to run a relatively time consuming script based on some form input, but I'd rather not resort to cron, so I'm wondering if a php page requested through ajax will continue to execute until completion or if it will halt if the user leaves the page.
It doesn't actually output to the browser until a json_encode at the end of the file, so would everything before that still execute?
It depends.
From http://us3.php.net/manual/en/features.connection-handling.php:
When a PHP script is running normally
the NORMAL state, is active. If the
remote client disconnects the ABORTED
state flag is turned on. A remote
client disconnect is usually caused by
the user hitting his STOP button.
You can decide whether or not you want
a client disconnect to cause your
script to be aborted. Sometimes it is
handy to always have your scripts run
to completion even if there is no
remote browser receiving the output.
The default behaviour is however for
your script to be aborted when the
remote client disconnects. This
behaviour can be set via the
ignore_user_abort php.ini directive as
well as through the corresponding
php_value ignore_user_abort Apache
httpd.conf directive or with the
ignore_user_abort() function.
That would seem to say the answer to your question is "Yes, the script will terminate if the user leaves the page".
However realize that depending on the backend SAPI being used (eg, mod_php), php cannot detect that the client has aborted the connection until an attempt is made to send information to the client. If your long running script does not issue a flush() the script may keep on running even though the user has closed the connection.
Complicating things is even if you do issue periodic calls to flush(), having output buffering on will cause those calls to trap and won't send them down to the client until the script completes anyway!
Further complicating things is if you have installed Apache handlers that buffer the response (for example mod_gzip) then once again php will not detect that the connection is closed and the script will keep on trucking.
Phew.
It depends on your settings - usually it will stop but you can use ignore_user_abort() to make it carry on.
Depending on the configuration of the web server and/or PHP, the PHP process may, or may not, kill the thread when the user terminates the HTTP connection. If an AJAX request is pending when the user walks away from the page, it is dependent on the browser killing the request (not guaranteed) ontop of your server config (not guaranteed). Not the answer you want to hear!
I would recommend creating a work queue in a flat file or database that a constantly-running PHP daemon can poll for jobs. It doesn't suffer from cron delay but keeps CPU/memory usage to a usable level. Once the job is complete, place the results in the flat file/database for AJAX fetch. Or promise to e-mail the user once the job is finished (my preferred method).
Hope that helps
If the client/user/downloader/viewer aborts or disconnects, the script will keep running until something tries do flush new data do the client. Unless you have used
ignore_user_abort(), the script will die there.
In the same order, PHP is unable to determine if client is still there without trying to flush any data to the httpd.
found the actual solution for my case of it not terminating the connection. The SESSION on my Apache/Php server needed to close before the next one could start.
Browser waits for ajax call to complete after abort.

Categories