Thursday, June 19, 2014

How to execute part of PHP code Asynchronously

execute php code asynchronously

Suppose you have written some PHP code which performs series of tasks when a story is submitted, this will affect the usability of the system as user have to wait long times before their post can be submitted. The solution to this problem is to move time consuming PHP code into a separate file and call that file asynchronously through socket connection in PHP.

The flow is like this:

(Before Any Changes)

filename: post.php

//some php code
//some php code

//some time consuming php code
sleep(20);
$filename = 'article.txt';
$data = 'onlinetechtutorials.com';
file_put_contents($filename, $data);

//some php code

(After Calling Time Consuming PHP Code Asynchronously)

filename: post.php

//some php code
//some php code

//some time consuming php code
$filename = 'article.txt';
$data = 'onlinetechtutorials.com';
post_async('http://localhost/onlinetechtutorials/post_async.php',array('filename'=>$filename,'data'=>$data));
/**
 * 
 * @param String $url
 * @param Array $params
 */
function post_async($url, $params) {
    foreach ($params as $key => &$val) {
      if (is_array($val)) $val = implode(',', $val);
        $post_params[] = $key.'='.urlencode($val);
    }
    $post_string = implode('&', $post_params);
    $parts=parse_url($url);
    $fp = fsockopen($parts['host'],
        isset($parts['port'])?$parts['port']:80,
        $errno, $errstr, 30);
    $out = "POST ".$parts['path']." HTTP/1.1\r\n";
    $out.= "Host: ".$parts['host']."\r\n";
    $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out.= "Content-Length: ".strlen($post_string)."\r\n";
    $out.= "Connection: Close\r\n\r\n";
    if (isset($post_string)) $out.= $post_string;
    fwrite($fp, $out);
    fclose($fp);
}
//some php code

filename: post_async.php

extract($_POST);
file_put_contents($filename, $data);

Watch Video Tutorial of executing part of PHP code Asynchronously