How to execute shell commands synchronously in PHP

PHP exec will wait until the execution of the called program is finished, before processing the next line, unless you use & at the end of the string to run the program in background.


If I'm getting you right, you're executing php scripts from inside a php script.

Normally, php waits for the execution of the exec ("php phpscript1.php"); to finish before processing the next line.

To avoid this, just redirect the output to /dev/null or a file and run it in background.

For example: exec ("php phpscript1.php >/dev/null 2>&1 &");.


Check out the exec function syntax on php.net. You will see that exec does not run anything asynchronously by default.

exec has two other parameters. The third one, return_var can give you a hint if the script ran successfully or any exception was fired. You can use that variable to check if you can run the succeeding scripts.

Test it and let us know if it works for you.


In my opinion, it would be better to run cronjobs. They will execute synchronously. If the task is "on-the-fly", you could execute the command to add this cronjob. More information about cronjobs: http://unixgeeks.org/security/newbie/unix/cron-1.html

http://service.futurequest.net/index.php?_m=knowledgebase&_a=viewarticle&kbarticleid=30