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

Yesterday I wrote this post explaining how short goo.gl URLs can be expanded using the newly launched goo.gl 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 = 'http://goo.gl/WlFX';
$apiKey = 'your_api_key_here';

$curlObj = curl_init();

curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url?shortUrl='.$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);

curl_close($curlObj);
$json = json_decode($response);

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

And here is the full JSON response:

{
 "kind": "urlshortener#url",
 "id": "http://goo.gl/WlFX",
 "longUrl": "https://www.packtpub.com/php-jquery-cookbook-to-create-interactive-web-applications/book",
 "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. Pingback: PHP class for expanding and shortening URLs using Google URL shortener API | vijayjoshi.org

  2. duplicate file remover

    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!

    Reply