En las redes sociales se suele escribir de forma corta, normalmente estamos en la cantidad de caracteres por lo que sean hecho famosos los servicios para crear Shortlink o Enlaces cortos.
He creado dos funciones para crear Shortlinks utilizando los servicios Bit.ly y TinyURL.
Función: cURL
/**
* Función cURL
*
* @param string $url
* @return string
*/
function get_contents_curl( $url ) {
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_URL, $url );
$data = curl_exec( $ch );
if ( $data === FALSE ) {
$data = "Error cURL: " . curl_error( $ch );
}
curl_close( $ch );
return $data;
}
Servicio: Bit.ly
Para poder utilizar el servicio de Bit.ly es necesario crear una cuenta ya que necesitaremos un Nombre de usuario y una App Key que encontraremos en la dirección http://bit.ly/account/.
/**
* Bit.ly
*
* @uses get_contents_curl( $url )
*
* @param string $url
* @param string $login
* @param string $appkey
* @return string bit.ly
*/
function getBity( $url, $login, $appkey ) {
$bitly = 'http://api.bit.ly/v3/shorten?login=' . $login . '&apiKey=' . $appkey . '&longUrl=' . urlencode( $url ) . '&format=xml';
$response = get_contents_curl( $bitly );
$xml = simplexml_load_string( $response );
return $xml->data->url;
}
// El nombre de usuario y app key son inventados. echo getBitly( 'http://snippets-tricks.org/shortlinks-bitly-tinyurl-php/', 'maquero', 'R_p3579otha25k96348iu49y6549po5ggg' );
Con este servicio obtendré el siguiente enlace:
http://bit.ly/boTJDo
Este servicio nos permite personalizar los Shortlinks con nuestros propio dominios. Por ejemplo: Los enlaces de Snippets-Tricks utilizan el dominio snipt.me para crear Shortlinks, en este caso Bit.ly asignara el siguiente enlace:
http://snipt.me/bzmp4j
Servicio: TinyURL
/**
* TinyURL
*
* @uses get_contents_curl( $url )
*
* @param string $url
* @return string tinyurl
*/
function getTinyUrl( $url ) {
$tinyurl = get_contents_curl( "http://tinyurl.com/api-create.php?url=" . $url );
return $tinyurl;
}
Este servicio es más simple ya que solo necesitamos especificar la URL:
echo getTinyUrl( 'http://snippets-tricks.org/shortlinks-bitly-tinyurl-php/' );
Con este servicio obtendremos el Shortlink:
http://tinyurl.com/28qtqvo