Friday, 29 January 2016

CURL

Example:

In previous post i gave introduction of CURL now i will tell how we can create simple api system using CURL :


<?php 
//Your Website URL where You Have json response data
$url = "http://php-guidelines.blogspot.com/";    

//here we can use key for security purpose
$key ='xyzkey';

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));// we want in response format json
curl_setopt($curl, CURLOPT_POST, true);//our services using post method
curl_setopt($curl, CURLOPT_POSTFIELDS, $key);//enter value of post field

$json_response = curl_exec($curl); //it will execute curl statement

//get response code eg 404,505 etc..
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
//if response is not success show a failure message with response code

if ( $status != 200 ) {
/*die("Error: call to URL $url failed with status $status, , curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));*/
$response=array("Response" =>$status,"Message"=>"Request Failed" );
echo json_encode($response);
die();

}

//if success show data to user
curl_close($curl);
$app_info =json_decode($json_response);
?>