How to run a php script in the background

While working in PHP project, sometimes we need to have such script that to much time in execution. Tasks like sending mails, big database process or file creation can be set to execute in background so the next process can be executed and don't need to wait for next process.

In PHP there are many ways you can do this in background. There are plenty of packages available to do such task. But many of us want to do self for learning. There are also many ways we can do this with PHP also.

Here are some ways that I have come to know to do this. The first way is to execute the command. In the Linux system it can be done with bellow code.

exec ('/usr/bin/php path/to/script.php >/dev/null &');

If you want to work with Windows system also, then first we have to check system OS and run the command according to it.


function backgroundProcess($cmd) {
    // windows
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r")); 
    // linux
    } else {
        exec($cmd . " > /dev/null &");  

This will execute $cmd in the background without PHP waiting for it to finish, on both Windows and Linux.

If you have any suggestions please make comment bellow, would be much appreciated.