PHP: How to Shorten an URL using the Google URL Shortener API Programming 22 FEB 2013

The shortening of URLs has become quite popular as the advancement of mobile phones picked up speed, and for the most part the science of generating a short URL given a long URL is pretty elementary stuff.

Today’s PHP function looks at how one can quickly generate a short URL from a long URL by making use of Google’s excellent URL Shortener API.

Now of course, requests to the Google URL Shortener API for public data must be accompanied by an identifier, which can be an API key or an auth token. 99% of the time an API key will suffice for your purposes, so to acquire an API key, visit the APIs Console and in the Services pane, activate the Google URL Shortener API. Next, go to the API Access pane. The API key is near the bottom of that pane, in the section titled “Simple API Access.”

After you have an API key, your application can append the query parameter key=yourAPIKey to all request URLs. Note that the API key is safe for embedding in URLs – it doesn’t need any encoding.

Now that we have our API key, let’s take a look at the function which is going to generate our Short URLs for us:

//generate a short URL using Google URL Shortening API
function googleGenerateShortURL($longurl) {
    //result object to be returned at the end of the function
    $result = array('status' => '0', 'short-url' => '', 'long-url' => '', 'message' => 'Failed to shorten URL.');

    if (strlen($longurl) > 0) {

        //build up the options array to be fed into the stream_context object
        $opts = array('http' =>
                'method' => 'POST',
                'header' => "Content-type: application/json\r\nX-Requested-With: XMLHttpRequest\r\n",
                'content' => json_encode(array('longUrl' => $longurl, 'key' => '#YOUR-GOOGLE-API-KEY#'))

        //attempt to hit the Google API url using a file_get_contents call using our crafted stream context
        try {
            //create stream context using our special options
            $context = stream_context_create($opts);
            $queryreturn = file_get_contents("", false, $context);
            //decode the returned JSON object
            $jsondata = json_decode($queryreturn, true);

            if ((key_exists('id', $jsondata)) && (strlen($jsondata['id']) > 0)) {
                $result = array('status' => '1', 'short-url' => $jsondata['id'], 'long-url' => $jsondata['longUrl'], 'message' => 'Succesfully generated short URL.');
        } catch (Exception $e) {
            $result['message'] = 'Failed to shorten URL. Unable to connect to Google\'s API service.';
            $result['exception'] = $e->getMessage();
    } else {
        $result['message'] = 'Failed to shorten URL. No long URL provided.';
    return $result;

If successful, the function will contain a ‘status’ set to 1, as well as the shortened URL stuffed into the ‘short-url’ key of the function return object.

So not exactly rocket science then, but definitely something rather nifty and even better, time saving!

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.