Google URL Shortener API Example using PHP and CURL

URL shortening is a technique that substantially shortens a url in length by creating a new url that when accessed, redirects the user to the original url. Another use for url shortening might be to disguise the original url… I recently needed to generate shortened urls and decided to try out the Google URL Shortener API. Signing up for a free API key allows up to 1,000,000 queries per day.

$google_api_key = 'INSERT_YOUR_API_KEY_HERE';
 
$long_url = 'http://www.domain.com/?utm_source=PHP%2BFunctionalism&utm_medium=post&utm_campaign=PHP%2BFunctionalism';
 
$short_url = shorten($long_url,$google_api_key);

The php fucntion to integrate with the Google URL Shortener API using PHP and CURL. For the json_decode() and json_encode() functions you will need PHP 5.2+.

function shorten($url,$key){
 
	$ch = curl_init();
 
	curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/urlshortener/v1/url?key={$key}");
 
	curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
	curl_setopt($ch, CURLOPT_POST, true);
 
	curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('longUrl' => $url)));
 
	$result = curl_exec($ch);
 
	$json = json_decode($result);
 
	curl_close($ch);
 
	return $json->id;
 
}

About this entry