AMPEDUPDESIGNS

CONSULTING CONCEPTS PERSONAL

Running PHP scripts in the background in Windows

August 9th, 2014

So trying to run a background PHP script so you can fire off multiple concurrent scripts? A great example is letting an admin user fire off a db processing script that would need to run for a long time.  While doing the same in a linux environment is sort of a breeze using the php exec function (don't forget to redirect the output somewhere),  I discovered that in Windows, the same code didn't work,  php consistently kept waiting for the script to finish, thereby essentially locking up the sessioned user.  After searching high and low and coming across various answers that didn't work, I finally found a combination that worked for me:

if (substr(php_uname(), 0, 7) == "Windows"){
     pclose(popen('start /B php.exe yourphpscript.php 2>nul >nul', "r")); 
}
else {
     exec('yourphpscript.php' 2>nul >nul');
}

The code above works on both windows and linux servers.  The key for Windows was to use the "start /B" command switch and also to output both error and regular results to nul "2>nul >nul".  

Now you should be able to run this in your php process, and fire off as many multiple concurrent php scripts at the same time.

Hope that helps!



Popular Posts