Friday, January 29, 2016

Implement asynchronous processes in PHP

Implement asynchronous processes in PHP:


One of the main reasons we need asynchronous processes in PHP is to allow something very time consuming to happen in the background, but not keep the client “on hold” for that entire duration; as PHP is typically synchronous, anything that takes a long time on the server will appear to take a long time for the client.

In that scenario, one solution would be to “detach” the client from the currently loading page, and let them have control of their browser back while the PHP script continues to do it's thing. We should be able to make this happen by sending some headers to the client to say “ok, we’re done here, connection ends”, even though PHP is still running.




class Service
{
    const HEADER_NEW_LINE = "\r\n";

    public function store()
    {
        /*code for reduce process time*/
        self::closeConnection('true');
       //do your code that take much more time e.g. upload a video or import an excel that take more time
    }

    public static function closeConnection($instantOutput = '') {
        set_time_limit(0);
        ignore_user_abort(TRUE);
        header('Connection: close' . self::HEADER_NEW_LINE);
        header('Content-Encoding: none' . self::HEADER_NEW_LINE);
        ob_start();
        echo $instantOutput;
        $size = ob_get_length();
        header('Content-Length: ' . $size, TRUE);
        ob_end_flush();
        ob_flush();
        flush();
    }
}




There are another way to implement asynchronous in php like open socket, log file, fork a curl process etc, but as per my requirement i did choose this 'detach client' method, you are free to choose any method as per your requirement.

Thanks.

No comments:

Post a Comment