• Easily create short URLS with php, curl and goo.gl.

    The 140 character limit in twitter has made it necessary to use URL services to make the URL short.
    There are many URL shortening services available like http://goo.gl, http://bit.ly, http://ow.l etc. If you have an extremely long URL and need to shorten it up for print, social media, television, or other advertising to help make it memorable, then a custom shortened URL is probably the way to go for you.

    It is easy to create short URL’s with Google’s URL shortening service, http://goo.gl. Use the following code. You need to have curl enabled in your server. You also need to get an API Key from http://code.google.com/apis/console/

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    
    function goo_gl_short_url($longUrl)
    {
    $GoogleApiKey = 'AIzaSyCrHbcPs4aT52MMZiBTHKEo3-ZqDuxRckI';
     
    $postData = array('longUrl' => $longUrl, 'key' => $GoogleApiKey);
     
    $jsonData = json_encode($postData);
     
    $curlObj = curl_init();
     
    curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
     
    curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
     
    //As the API is on https, set the value for CURLOPT_SSL_VERIFYPEER to false. This will stop cURL from verifying the SSL certificate.
     
    curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
     
    curl_setopt($curlObj, CURLOPT_HEADER, 0);
     
    curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
     
    curl_setopt($curlObj, CURLOPT_POST, 1);
     
    curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
     
    $response = curl_exec($curlObj);
     
    $json = json_decode($response);
     
    curl_close($curlObj);
     
    return $json->id;
    }
    Tags:

Comments on this post

Leave a Reply

  • Security Code :


    − 1 = six