PHP supports a technology known as cURL. cURL is a command line tool to enable data to be transferred via various protocols and has also been integrated into PHP. For PHP developers this means that cURL is a way to request data from other servers via GET and POST.

If you are familiar with AJAX Cross Domain techniques you’ll know that the browser can make a request for data from a third party. With cURL the request for third party data comes directly from server rather than the client. This is particularly useful as it allows the developer to hide away information like API keys which would otherwise be exposed by client side Javascript.

cURL Functions

To use cURL in PHP requires three steps. Firstly, create your cURL session with the curl_init() method. This can optionally take the URL of the resource you wish to request as its parameter.

$myCurl = curl_init('http://www.somewhere.com/resource.json'); 

Secondly, we need to set the options for the cURL session using the curl_setopt() method.

curl_setopt(CURL SESSION, OPTION NAME, VALUE);

This can include the URL of the resource if you didn’t initialize that with curl_init() ie:

$myCurl = curl_init(); 
curl_setopt($myCurl, CURLOPT_URL, "http://www.somewhere.com/resource.json"); 

There are a huge range of options for your cURL request, the headlines options are:

CURLOPT_URL
to set the target URL
CURLOPT_RETURNTRANSFER
if true returns value as a string to be manipulated
CURLOPT_CONNECTTIMEOUT
maximum number of seconds to allow for the call. Use 0 to wait indefinitely
CURLOPT_FAILONERROR
fails silently
CURLOPT_POST
if true request made with HTTP POST
CURLOPT_POSTFIELDS
data to sent as an array of name/value pairs

Finally execute the call for the data using the curl_exec() which takes the cURL session as it parameter.

<?php 
$myCurl = curl_init(); 
curl_setopt($myCurl, CURLOPT_URL, "http://www.somewhere.com/resource.json"); 
curl_setopt($myCurl, CURLOPT_FAILONERROR, 1); 
curl_setopt($myCurl, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($myCurl, CURLOPT_CONNECTTIMEOUT, 0); 
$result = curl_exec($myCurl); 
echo $result; 
?>

Example of where to use cURL

So why and where would you use this technique? In this example I want to reference the Flickr API to extract some photographs. To use the Flickr API I have to register and acquire an API key. If I choose to use Javascript and AJAX to connect to Flickr I would have no choice but to expose my API key in my Javascript. However, if I make the call to Flickr with cURL I can keep my API server side and not expose it to other web users.

Here is the PHP.

<?php
$json_url = 'http://api.flickr.com/services/rest/?api_key=MYKEY-NOT-FOR-YOU&method=flickr.photos.search&per_page=1&text=cats&format=php_serial';
$headers = array();
$headers[] = 'Content-type: application/json';
$headers[] = 'X-HTTP-Method-Override: GET';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $json_url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($headers));
curl_setopt($ch, CURLOPT_HEADER, 0);
// Getting jSON result string
$result =  curl_exec($ch); 
if($result === false || curl_error($ch)) {
   curl_close($ch);
} else {
   curl_close($ch);
   $rsp_obj = unserialize($result);
   $json = json_encode($rsp_obj);
   echo $json;                 
}
?>

A few things worthy of note here. Obviously in the above MYKEY-NOT-FOR-YOU would be your key. As part of the API call we send a name / value pair of format=php_serial. This is an option in the Flickr API that will returned data to use in a serialized fashion. As such we have to use unserialize() and json_encode() to get the JSON we want. And yes we are using text=cats because we want a picture of a cat.

Next we call the PHP outlined above with standard Javascript AJAX ie:

function showImg() {
    var myJson  = JSON.parse(myXHR.responseText);
    var farm = myJson.photos.photo[0].farm;
    var server = myJson.photos.photo[0].server;
    var id = myJson.photos.photo[0].id;
    var secret = myJson.photos.photo[0].secret;
    var img = 'http://farm'+farm+'.staticflickr.com/'+server+'/'+id+'_'+secret+'.jpg';
	document.getElementById('flickPic').setAttribute('src', img);
}

var myXHR=new XMLHttpRequest();
myXHR.onload = showImg;
myXHR.open("GET","curl-flickr-call.php", true);
myXHR.send(null);

The JSON returned comes from Flickr but via our PHP cURL script. The JSON returned I have called ‘myJson’ and the bulk of the code above relates to then getting the image data out of the JSON, and then using it to then call one of Flickr server farms for the image.

View The Demo

One Thought to “cURL”

  1. […] cURL – Must Be Built – PHP supports a technology known as cURL. cURL is a command line tool to enable data to be transferred via various protocols and has also been integrated into PHP…. […]

Leave a Comment