Using PHP and cURL to expand URLs using Google URL shortener API

Yesterday I wrote this post explaining how short URLs can be expanded using the newly launched API. In that code we used php function get_file_contents to get the response from API.

How about implementing the same functionality using cURL now? If you have libcurl support installed with PHP, you are ready to use the cURL functions of PHP.

Here is the code. API key is not mandatory but Google recommends that you use one. It will increase your per day usage limits too. Follow this link to get an API key.

$shortUrl = '';
$apiKey = 'your_api_key_here';

$curlObj = curl_init();

curl_setopt($curlObj, CURLOPT_URL, ''.$shortUrl.'&key='.$apiKey);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);

$response = curl_exec($curlObj);

$json = json_decode($response);

if($json->status === "OK")
	echo $json->longUrl;
	echo 'Bad luck.';

And here is the full JSON response:

 "kind": "urlshortener#url",
 "id": "",
 "longUrl": "",
 "status": "OK"

Am important point to note. Since the API is on https, set the value for CURLOPT_SSL_VERIFYPEER to false. This will stop cURL from verifying the SSL certificate.

4 thoughts on “Using PHP and cURL to expand URLs using Google URL shortener API”

  1. Hey there! I’ve been reading your web site for some time now and finally got the courage to go ahead and give you a shout out from Dallas Tx! Just wanted to say keep up the good job!

Leave a Reply