Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can PHP scripts continue to run even if the user closed the browser?

Tags:

php

For example, there is a very simple PHP script which updates some tables on database, but this process takes a long time (maybe 10 minutes). Therefore, I want this script to continue processing even if the user closed the browser, because sometimes users do not wait and they close the browser or go to another webpage.

like image 829
Oguz Bilgic Avatar asked Nov 01 '09 21:11

Oguz Bilgic


People also ask

Can a PHP script run forever?

You can make it run forever by either setting the value or call set_time_limit in your script (http://php.net/manual/en/function.set-time-limit.php).

Does PHP run in browser or server?

Chapter 1. PHP: What, Why, and Where? PHP is ultimately just text that is taken by your web server and turned into a set of commands and information for your web browser. And because you're just working in text, there's not a lot you have to do to get going as a PHP programmer.

Why PHP script is not running in browser?

PHP is not intended for execution in a browser. It is for web servers to execute, or other preprocessing on the PHP-installed computer. PHP runs in several incarnations when installed on a computer: from the command line.

How do I know if a PHP script is running?

Check if a PHP script is already running If you have long running batch processes with PHP that are run by cron and you want to ensure there's only ever one running copy of the script, you can use the functions getmypid() and posix_kill() to check to see if you already have a copy of the process running.


2 Answers

If the task takes 10 minutes, do not use a browser to execute it directly. You have lots of other options:

  • Use a cronjob to execute the task periodically.
  • Have the browser request insert a new row into a database table so that a regular cronjob can process the new row and execute the PHP script with the appropriate arguments
  • Have the browser request write a message to queue system, which has a subscriber listening for such events (which then executes the script).

While some of these suggestions are probably overkill for your situation, the key, combining feature is to de-couple the browser request from the execution of the job, so that it can be completed asynchronously.

If you need the browser window updated with progress, you will need to use a periodically-executed AJAX request to retrieve the job status.

like image 70
DavidWinterbottom Avatar answered Oct 01 '22 00:10

DavidWinterbottom


To answer your question directly, see ignore_user_abort

More broadly, you probably have an architecture problem here.

If many users can initiate this stuff, you'll want the web application to add jobs to some kind of queue, and have a set number of background processes that chew through all the work.

like image 17
timdev Avatar answered Oct 01 '22 00:10

timdev