Friday, June 12, 2009

Using CURL as HTTP Client for XmlRPC in PHP

From my previous post, about modification of IXR XmlRPC client to add HTTPS capability, I used function fopen as a HTTP/S client. This technique can only be applied for PHP ver 5.0 or above. So, in this post, I will try to use CURL as a more attractive alternative for all PHP version that support CURL extention. CURL itself is known as stable and powerful multi protocol (including HTTP/S) client for command line in linux world. Thanks to the extension capability of PHP, we can utilize the power of CURL inside PHP directly. So here is the code for SendHttpPost method using CURL:

function SendHttpPost($url,$content){

$ch = curl_init(); // initialize curl handle

curl_setopt($ch, CURLOPT_VERBOSE, 0); // set url to post to
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 40); // times out after 4s
curl_setopt($ch, CURLOPT_POSTFIELDS, $content); // add POST fields
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST ,0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

$result = curl_exec($ch); // run the whole process

if (empty($result)) {
// some kind of an error happened
//die(curl_error($ch));
//curl_close($ch); // close cURL handler

} else {
$info = curl_getinfo($ch);
//curl_close($ch); // close cURL handler

if (empty($info['http_code'])) {
//die("No HTTP code was returned");
} else {
// load the HTTP codes
// $http_codes = parse_ini_file("response.inc");
// echo results
//echo "The server responded: \n";
//echo $info['http_code'] . " " . $http_codes[$info['http_code']];
}
}

curl_close($ch);
return $result; //contains response from server

}



No comments:

Post a Comment