How to run a php script in the background

  5 months ago     Views:  465  
Julius Braun
1 Follows


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.


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

2 Comments

  • Image
    온라인카지노
    May 28, 2020 Reply

    I'm impressed, I have to admit. Seldom do I come across
    a blog that's both educative and interesting, and without a doubt, you've hit the nail on the head.
    The problem is something too few people are speaking intelligently about.
    Now i'm very happy I found this during my search for something regarding this. https://uricasino114.com

  • Image
    Marianne
    May 18, 2020 Reply

    I’ve been browsing online more than three hours these days, yet I never found any attention-grabbing article like yours.
    It is beautiful value enough for me. In my view, if all website owners and bloggers made excellent content material as you probably
    did, the net can be much more helpful than ever before.
    Ahaa, its good discussion on the topic of this post
    here at this weblog, I have read all that, so now me also commenting at
    this place. Thank you for the auspicious writeup.
    It in fact was a amusement account it. Look advanced to far added
    agreeable from you! However, how can we communicate?
    http://cars.com/