Google posee un dominio que utiliza para acortar URLs desde hace ya un tiempo, pero hasta ahora no hab?a echo publico una API para que pudieramos beneficiarnos de esta -indispensable- herramienta, y desde el blog de David Walsh me entero de una clase que con un poco de c?digo PHP podemos acortar una URL sin ning?n problema.
Esta es la clase:
class GoogleUrlApi { // Constructor function GoogleURLAPI($key,$apiURL = 'https://www.googleapis.com/urlshortener/v1/url') { // Keep the API Url $this->apiURL = $apiURL.'?key='.$key; } // Shorten a URL function shorten($url) { // Send information along $response = $this->send($url); // Return the result return isset($response['id']) ? $response['id'] : false; } // Expand a URL function expand($url) { // Send information along $response = $this->send($url,false); // Return the result return isset($response['longUrl']) ? $response['longUrl'] : false; } // Send information to Google function send($url,$shorten = true) { // Create cURL $ch = curl_init(); // If we're shortening a URL... if($shorten) { curl_setopt($ch,CURLOPT_URL,$this->apiURL); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url))); curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json")); } else { curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url); } curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); // Execute the post $result = curl_exec($ch); // Close the connection curl_close($ch); // Return the result return json_decode($result,true); } }
Para utilizarla necesitamos una clave de Google API.
Y esta es la forma de usarla:
// Primero intanciamos la clase $key = 'xhjkhzkhfuh38934hfsdajkjaf'; $googer = new GoogleURLAPI($key); // Acortamos una URL $shortDWName = $googer->shorten("http://davidwalsh.name"); echo $shortDWName; // returns http://goo.gl/i002 // Y con esto expandimos una URL acortada a su original $longDWName = $googer->expand($shortDWName); echo $longDWName; // returns http://davidwalsh.name
Los m?todos shorten() y expand() devuelven sus contrapartes. Esta clase proporciona solamente lo b?sico ya que la API nos da mas cosas, como lista de URL y seguimiento de su uso.
FUENTE: David Walsh Blog