ISSUE :
 
Profile photo
Submitted by Sam Buchana
on July 8th, 2011 at 15:40:17 EST

How to make Asynchronous http calls using PHP?

Is there a standard way to make async calls using php? I am looking for an approach to make asynchronous call from my php application. Actually I need to write metrics log so I really don't care about the response. I just need to trigger another call asynchronously.


Profile photo
Replied by SBajra
on July 11th, 2011 at 10:13:39 EST
Try this using fsockopen()
<?php
//Calling http url asynchronously with parameters
async_call('http://localhost/php/test1.php';, 'test=something&category=somecategory');

/*
Make Async http call
$url = Url to make Async call e.g. http://www.somesite.com or http://www.somesite.com:80
$paramstring = Parameter string in the format of querystring with name=value separated by "&" e.g.: name1=value1&name2=value2
$method = "GET" or "POST"
$timeout = Timeout in seconds. Default 30 seconds
$returnresponse = true/false. Default false. If true, waits for response and return back response data.
*/
function async_call($url, $paramstring, $method='get', $timeout='30', $returnresponse=false)
{
$method = strtoupper($method);
$urlParts=parse_url($url);
$fp = fsockopen($urlParts['host'],
isset($urlParts['port'])?$urlParts['port']:80,
$errno, $errstr, $timeout);

//If method="GET", add querystring parameters
if ($method='GET')
$urlParts['path'] .= '?'.$paramstring;

$out = "$method ".$urlParts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$urlParts['host']."\r\n";
$out.= "Connection: Close\r\n";

//If method="POST", add post parameters in http request body
if ($method='POST')
{
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($paramstring)."\r\n\r\n";
$out.= $paramstring;
}

fwrite($fp, $out);

//Wait for response and return back response only if $returnresponse=true
if ($returnresponse)
{
echo stream_get_contents($fp);
}

fclose($fp);
}
?>
Accepted Answer
Accepted
 Answer

Profile photo
Replied by Sam Buchana
on July 11th, 2011 at 12:01:17 EST
This works. And this exactly solves my problem. Thanks.