PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Shortening URLs for goo.gl with Google's URL Shortener API

In 2010 Google released its own URL shortener, which allows you to shorten URLs to use the goo.gl domain. In this article I will show you how to easily create your own short URLs using their new URL shortener API.

Note: This API is still in labs, meaning the API is subject to change without notice.

The Google URL Shortener API allows you to do the following:

  • Create a new short URL
  • Retrieve info about a short URL (such as the full URL and various analytics)
  • Retrieve a list of shortened URLs for a given user
Note: To retrieve a list of shortened URLs an OAuth token is required to authenticate the user. Additionally, you must be authenticated in the same way when creating the URL in order for it to be linked to the given account. To simplify this article we will not be covering this aspect of the API.

We will use the cURL library to perform the required HTTP requests to make use of this API. Additionally, JSON data is extensively used for both requests and responses, so we will use the json_encode() and json_decode() functions accordingly.

Creating an API Key

To use the Google URL Shortener API you must have an API key. To get an API, key, follow these instructions:

  1. Visit the Google APIs console
  2. Create a project
  3. Activate the URL Shortener API
  4. Click Keys in the left navigation. You can then copy and paste the key from this page
Note: You can perform a limited number of API calls without a key. This may be useful during development.

Creating a Short URL

To create a shortened URL, post to https://www.googleapis.com/urlshortener/v1/url?key=key.

Rather than posting traditional form fields, we post JSON data instead. As such, we must also set the correct content type header for the request. Usually for post requests this is application/x-www-form-urlencoded, but we're posting JSON data so we use application/json.

To begin, let's define the API key and endpoint URL. The call we're making isn't the only API call available, so we define the base URL endpoint so it can be used for other calls too.

Listing 1 Defining the API key and API endpoint (listing-1.php)
<?php
    define('GOOGLE_API_KEY', '[insert your key here]');
    define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');
?>

Next, we define the shortenUrl function. This function accepts the long URL you want shortened and returns an array which holds the long and short URLs.

Listing 2 Defining the shortenUrl() function and initializing the cURL connection (listing-2.php)
<?php
    function shortenUrl($longUrl)
    {
        // initialize the cURL connection
        $ch = curl_init(
            sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
        );
 
        // tell cURL to return the data rather than outputting it
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
        // ... more code will go here
    }
?>

Here we initialize the cURL connection for our HTTP request. We build the URL from the endpoint and our API key and pass it as the first argument to curl_init().

Additionally, we set the CURLOPT_RETURNTRANSFER option to true. If we don't do this, we can't decode the returned JSON data. Instead, it will be output directly.

Next we must build the request data. As mentioned previously, the request must be a POST request which contains JSON data as the post body.

To create a new shortened URL, a single parameter called longUrl is required. The corresponding value should the URL to shorten. The following list demonstrates how we set the request to post JSON data.

Listing 3 Setting the cURL connection to post JSON data (listing-3.php)
<?php
    function shortenUrl($longUrl)
    {
        // ... other code
 
        // create the data to be encoded into JSON
        $requestData = array(
            'longUrl' => $longUrl
        );
 
        // change the request type to POST
        curl_setopt($ch, CURLOPT_POST, true);
 
        // set the form content type for JSON data
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
 
        // set the post body to encoded JSON data
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
 
        // ... other code
    }
?>

At this point, the cURL request is all set-up and ready to go. We can now excecute the request. The following listing demonstrates how to achieve this.

Listing 4 Performing the cURL request and decoding the response (listing-4.php)
<?php
    function shortenUrl($longUrl)
    {
        // ... other code
 
        // perform the request
        $result = curl_exec($ch);
        curl_close($ch);
 
        // decode and return the JSON response
        return json_decode($result, true);
    }
?>

Since this web service returns JSON data, we can turn it into a native PHP array using json_docode(). The second argument of true instructs PHP to create an array (instead of an object).

Note: This code does not perform any error handling. Read about Google URL Shortener API error messages.

Finally, we can make use of the shortenUrl() function simply by passing it a URL. We can then output the returned shortened URL. The following listing demonstrates how this is achieved.

Listing 5 Using shortenUrl() and outputting the results (listing-5.php)
<?php
    $response = shortenUrl('http://phpriot.com');
 
    echo sprintf(
        '%s was shortened to %s',
        $response['longUrl'],
        $response['id']
    );
?>

The Complete Code Listing

The complete listing we constructed in this article is as follows. Remember to substitute in your own API key.

Listing 6 Complete code listing (listing-6.php)
<?php
    define('GOOGLE_API_KEY', '[insert your key here]');
    define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');
 
    function shortenUrl($longUrl)
    {
        // initialize the cURL connection
        $ch = curl_init(
            sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
        );
 
        // tell cURL to return the data rather than outputting it
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
        // create the data to be encoded into JSON
        $requestData = array(
            'longUrl' => $longUrl
        );
 
        // change the request type to POST
        curl_setopt($ch, CURLOPT_POST, true);
 
        // set the form content type for JSON data
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
 
        // set the post body to encoded JSON data
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
 
        // perform the request
        $result = curl_exec($ch);
        curl_close($ch);
 
        // decode and return the JSON response
        return json_decode($result, true);
    }
 
    $response = shortenUrl('http://phpriot.com');
 
    echo sprintf(
        '%s was shortened to %s',
        $response['longUrl'],
        $response['id']
    );
?>

Summary

In this article I showed you how to make use of the new Google URL Shortener API to generate your own short links on the goo.gl domain.

This API also allows you retrieve information and analytics about your shortened URLs. This requires only basic modifications to this script.

Further Reading

Other Options

Shortening URLs for goo.gl with Google's URL Shortener API