How to execute / run PHP scripts in the background?

If the website is run on a Linux server, everything that can be run from the web (i.e., from the browser address bar) can be run from the Linux console. That is if you have the SSH access which most hosts provide. Connect to your hosting server via SSH by putty and you will have the ultimate control over your box. For example, you can execute a PHP script called routine.php via SSH by:

/usr/bin/php5 routine.php #routine.php is in the current working directory

Depending on your distro and PHP installation options, the command line interpreter (in this case, /usr/bin/php5) may vary in location.

You can add this line to a crontab job and it the PHP script routine.php will be executed by your designated intervals or at any certain time, automatically.

Other than calling PHP scripts from Linux console via SSH, you can also call to execute PHP code in another script file from the current PHP file. For instance, in A.php:

exec('/usr/bin/php5 B.php');

As it obviously suggests, this line will run the Linux command ‘/usr/bin/php5 B.php’ and you can put stuff in B.php that will be taken care of when this line in A.php is executed.

There are a variety of different PHP functions that perform essentially the same task, running system commands: exec, shell_exec, system and passthru.

1 thought on “How to execute / run PHP scripts in the background?”

  1. For those occasions where you can’t use exec you have to get a bit tricky. One option that I’ve written about on our blog is using AJAX to call a script that will continue to run in the background and not impact the user’s browsing session.

Comments are closed.

Scroll to Top