How to run a php script in the background

2636 views 1 year ago PHP

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.

<?php
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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]