Google URL Shortener

Juyun Wang's picture

The Google URL Shortener is a service that takes long URLs and squeezes them into fewer characters to make a link that is easier to share, or email to friends. Google provides URL Shortener API for free with a daily limit of 1,000,000 queries.We can use the Google URL Shortener API to programmatically interact with this service and to develop applications that use simple HTTP methods to store, share, and manage goo.gl short URLs. Below is the example of Google URL Shortener APIwith PHP:

1. Get your API key : https://code.google.com/apis/console
2. Shorten a long URL

To send and get the json data we use the PHP cURL functions.

define ( 'API_KEY', 'AIzaSyB8NLUnMd4Vnhg7ee3FN0EMMXmC5cZlwLA' );
define ( 'API_URL', 'https://www.googleapis.com/urlshortener/v1/url' );

if (isset ( $_REQUEST ['url'] ) && ! empty ( $_REQUEST ['url'] ))
{

$longUrl = $_REQUEST ['url'];

// Create the data
$postData = array (
'longUrl' => $longUrl,
'key' => API_KEY
);

// Encoded into JSON
$jsonData = json_encode ( $postData );

// Initialize the cURL session
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, API_URL );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array ( 'Content-type:application/json' ) );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $jsonData );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );

// Execute the cURL session
$result = curl_exec ( $ch );

// Close the cURL session
curl_close ( $ch );
$shortUrl = json_decode ( $result );
echo $shortUrl->id;

}

We are creating a simple URL Shortener page example:

You can also call this method to expand any goo.gl short URL, or Look up a short URL's analytics. The Detail can refer to Google URL Shortener API official website: https://developers.google.com/url-shortener/?hl=zh-TW