Asynchronous Processing With PHP

Several weeks ago I was looking on line for a way to have PHP execute a background process, so that the page didn’t hang while some functionality happened. One way to do that is to use fsockopen() to open a url to exec what you want. But I wanted to see if there was another way. This is what I came up with.

I should note that this isn’t that well tested. I ran it on a Windows and Linux system without incident to test it, but I haven’t given it a very thorough exam. Also note $call is completely unsanitized. If you’re using this and accepting anything from the web, you need to make really sure that $call is completely sane and free of evil.

< ?php
/* Note that the call itself isn’t sanitized in any way, so it’s
   important to make sure that this can’t be exploited, see
   docs for escapeshellcmd() for details
*/
 
// Demonstration
if(launchBackgroundProcess(‘touch testfile.txt’)){
    print ‘Successfully launched background process’;
}
 
 
 
/**
* Launch Background Process
*
* Launches a background process (note, provides no security itself, $call must be sanitized prior to use)
* @param string $call the system call to make
* @author raccettura
*/
function launchBackgroundProcess($call) {
 
    // Windows
    if(is_windows()){
        pclose(popen(‘start /b ‘.$call., ‘r’));
    }
 
    // Some sort of UNIX
    else {
        pclose(popen($call.‘ /dev/null &’, ‘r’));
    }
    return true;
}
 
 
/**
* Is Windows
*
* Tells if we are running on Windows Platform
* @author raccettura
*/
function is_windows(){
    if(PHP_OS == ‘WINNT’ || PHP_OS == ‘WIN32’){
        return true;
    }
    return false;
}
?>

To run a php process you can obviously use launchBackgroundProcess('php /path/to/script.php');.

Now say we wanted to load a page while retrieving data from a process to display inline. We don’t want to wait for the entire command to finish, since that could take a while, and the user may believe something is wrong and reload (slowing down the system even more). A good example of this is an online traceroute utility. Here’s a quick example of that:

< ?php
    /****
     * Again notice this is unsanitized since we trust ourselves.  Coming from the web
     * it would need to be sanitized to ensure it’s safe to use.  see escapeshellarg()
     ****/
    $hostname = ‘accettura.com’;
?>
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Traceroute to $hostname</title>
</head>
<body>
< ?php
    if(is_windows()){
        $cmd = ‘tracert -w 10’;    
    } else {
        $cmd = ‘traceroute -w 10’;
    }
    $handle = popen("$cmd $hostname 2>&1", ‘r’);
 
    while(!feof($handle)) {
        $buffer = fgets($handle);
        $buffer = ‘<p>’.trim(htmlspecialchars($buffer)).‘</p>’;
 
        echo $buffer;
        ob_flush();
        flush();
    }
    pclose($handle);
 
 
 
   /**
    * Is Windows
    *
    * Tells if we are running on Windows Platform
    * @author raccettura
    */
    function is_windows(){
        if(PHP_OS == ‘WINNT’ || PHP_OS == ‘WIN32’){
            return true;
        }
        return false;
    }
?>
</body>
</html>

Isn’t that simple?

There’s more than 1 way to approach a problem, and there may be better ways out there. I won’t be so cocky as to think these are by any means perfect. But they may be of help to someone who also notices the lack of documentation on little (but important) things like this.

Just remember: always sanitize your input when working with stuff like this, or your putting your system at risk.

23 thoughts on “Asynchronous Processing With PHP

  1. Pingback: silentcoder.com » Blog Archive » Asynchronous Processing With PHP

  2. This looks good; I am trying to figure out a way to get a PHP script to run in the background on a Windows server.

    However, I can’t figure out your use of quotes, they seem to be uneven.

    What am I missing?

  3. Sean: you can use both ' or " in PHP as long as you use them as “This “.’that’. Single quotes won’t be evaluated. For example:

    $test = ‘value’;
     
    print "This is a $test"; // will be: This is a value
    print ‘This is a $test’; // will be: This is a $test
  4. Pingback: How To Run A PHP Script In The Background | MT-Soft Website Development

  5. this ain’t workin. any ideas? running on a linux host:

    if this is shelling out to the system, then i don’t have shell access. is there way way to do an asynchronous call to a php script WITHOUT calling the shell?

    thanks

  6. This doesn’t work with me. I don’t know what’s wrong, but lauchBackgroundProcess() doesn’t do anything. However, if I add fgets() as in the second script, it works. But, it’s not an asynchronous call!!

  7. I think the thing that was confusing ppl is the use of quotations in the following line:

    pclose(popen(‘start /b ‘.$call.”, ‘r’));

    This should actually be:

    pclose(popen(‘start /b ‘.$call, ‘r’));

    This also saved my day. Thanks man!

  8. I don’t see any asynchronous code.
    fgets ist waiting for input line.
    All you do is flushing php buffer (ob_flush(); flush()). There is no sense doing this in a pipe.
    Do something else instead of a traceroute(6) without response line by line and your code will wait unlimited.

  9. Pingback: Background Process in PHP | Ritvick Paliwal's Official Website

  10. Pingback: How To Run A PHP Script In The Background | W-Shadow.com

  11. Pingback: Run PHP Task Asynchronously - PHP Solution - Developers Q & A

  12. http://www.automaxplus.pl/2015/12/15/serwis-lpg
    Shopping for a new or used car can be a challenging approach unless you know what you are carrying out. By teaching yourself about vehicle purchasing prior to go to the dealership, you possibly can make stuff less difficult for yourself. The following advice will help your following shopping journey be more pleasurable.

    Constantly bring a technician together when buying a fresh automobile. Vehicle merchants are notorious for offering lemons and you may not wish to be their following target. Provided you can not get a technician to check out vehicles along, no less than ensure that you have him look at your final option before you purchase it.

    Know your limits. Before you begin shopping for your next car or pickup truck, choose what you can manage to pay, and stay with it. Don’t forget about to add curiosity about your computations. You will definitely pay out about twenty percent as an advance payment too, so be well prepared.

    Just before attending a dealership, know which kind of automobile you need. Study all you options ahead of store shopping so that you can figure out what works for your budget and household needs. Do your homework to determine just how much you need to be paying for any probable car.

    Prior to signing any deal spend some time to go through every single series, including the fine print. If you find nearly anything outlined that you just do not comprehend, do not signal up until you receive an solution that you understand. Unsavory salesmen are able to use a binding agreement to insert a lot of costs that have been not reviewed.

    In the event you maintain the previous advice in your mind the very next time that you go looking for a automobile, you will certainly be more prone to get a better bargain. Getting a auto lacks to be a headaches. Use the tips using this report and you may obtain the automobile you would like with a good cost.

  13. As soccer match games are going on, the competition is a more intensive now. Of course, the games are much more beautiful to football fans. But furthermore, it means the 2010 FIFA world cup games are going on the end. The most excited game will come up in next schedule as well.

    YouTube provides an easy for you to share videos with close friends and family online. However the videos are imprisoned web based with absolutely to save the videos to system computer hardrive. Is it really no in order to הורדת שירים מיוטיוב together with user’s computer hard journey? The answer is no and turn out to be easily implement it task.

    USTREAM VIDEOS: Watch the modern backstage is undoubtedly the red carpet in the 2011 Emmy Awards via UStream videos here: UStream Videos on the 62nd Annual Emmy Gives.

    UnPlug scans web pages and says to you where media players have become their data from, and allows a person easily save the media file. The icon of UnPlug always be at the statusbar, click it, the hyperlink of it will be decrypted, click “Download” to start downloading.

    Playing music in the transition of classes is often a great way to draw your students into the classroom, and music along with a historical bent can market curiosity and questioning within your students. To be the most effective, this music requires incorporate video – hopefully something that goes within the verse.

    It should be noted that Safari comes to Windows as well as Mac users can be a free download from Apple’s website. When your current browser struggle to download Flash video from YouTube after that you have free access to great browser that accomplishes this job for you.

    When the conversion is finished, the status can have you Gone through. It means you have downloaded World Cup game videos from Youtube at the moment. Actually, you can usana to download from other video-sharing websites, like Google video, Yahoo Video and so forth.
    mini-tracktor.ru

Leave a Reply

Your email address will not be published. Required fields are marked *