PHP Multiprocessing using built-in fork functions


You can use built-in functions to run PHP processes as forks. This is the most simple way to achieve parallel work if you don't need your threads to talk to each other.

This allows you to put time intensive tasks (like uploading a file to another server or sending an email) to another thread so your script loads faster and can use multiple cores but be aware that this is not real multithreading and your main thread won't know what the children are up to.

Note that under Windows this will make another command prompt pop up for each fork you start.


$cmd = "php worker.php 10";
if(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') // for windows use popen and pclose
else //for unix systems use shell exec with "&" in the end
    exec('bash -c "exec nohup setsid '.$cmd.' > /dev/null 2>&1 &"');


//send emails, upload files, analyze logs, etc
$sleeptime = $argv[1];