Wednesday, April 30, 2014

Simple Google URL Shortener PHP Class Wrapper

This is a simple PHP Class Wrapper using Google API URL

<?php

class GoogleUrlShortener 
{
        public $endPoint = 'https://www.googleapis.com/urlshortener/v1/url';
        public $key      = 'YOUR_GOOGLE_API_KEY';
        
        /* Shorten a long URL */
        function shorten($url)
        {
            $data = $this->execute($url,1);
            
            if(isset($data['id'])){
                    $result = $data['id'];
                }else{
                    $result = FALSE;
            }
            
            return $result;
        }
        
        /* Expand a short URL */
        function expand($url) 
        {
            $data = $this->execute($url,0);
            
            if(isset($data['longUrl'])){
                    $result = $data['longUrl'];
                }else{
                    $result = FALSE;
            }
            
            return $result;
        }
        
        /* Send Request to Google */
        function execute($url,$status) 
        {
            $curl           = curl_init();
            $googleApiUrl   = $this->endPoint.'?key='.$this->key;
            
            if($status == 1) {
                    curl_setopt($curl,CURLOPT_URL,$googleApiUrl);
                    curl_setopt($curl,CURLOPT_POST,1);
                    curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
                    curl_setopt($curl,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
                }else {
                    curl_setopt($curl,CURLOPT_URL,$googleApiUrl.'&shortUrl='.$url);
            }
            
            curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
            $res = curl_exec($curl);
            curl_close($curl);
            
            return json_decode($res,true);
        }    
}

Examples
  • Shorten URL
<?php

$shorten_my_url = new GoogleUrlShortener();
echo $shorten_my_url->shorten("http://wpmigrator.wordpress.com");
output : http://goo.gl/MZ4bW
  • Expand URL
<?php

$expand_my_url = new GoogleUrlShortener();
echo $expand_my_url->expand("http://goo.gl/MZ4bW");
output : http://wpmigrator.wordpress.com

No comments:

Post a Comment

Genesis Framework for WordPress