Blog de Gonzalo

ACORTAR URLS EN PHP

Siempre que escribo un post en mi blog se autopublica en twitter con la categoría del post como hastag así me ahorro el tener que publicarlo yo en twitter. Siempre se pone un enlace a la url del post para que la gente pueda leerlo y siempre ponía la url completa. Pero hoy he decidido usar el api de Google para acortar las url.
Para poder usar dicha api de Google lo que hay que hacer primero es conseguir el api key parala api url shortener en la url https://developers.google.com/url-shortener/v1/getting_started y ya se pueden obtener las urls cortas.
Un ejemplo sería:


$referer = 'http://tu-url.com';
$post_data = json_encode( array( 'longUrl'=>$long_url ) );
$ch= curl_init();
$arr = array();
array_push($arr, 'Content-Type: application/json; charset=utf-8');
curl_setopt($ch, CURLOPT_HTTPHEADER, $arr);
curl_setopt($ch, CURLOPT_URL,$api_url);
curl_setopt($ch, CURLOPT_REFERER, $referer);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if(curl_errno($ch))
{
throw new Exception(curl_error($ch));
}
curl_close($ch);
var_dump(json_decode($output));

Compartir en twitter