Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Last active October 31, 2019 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/af2efc1394b6d0214041c86516df88ae to your computer and use it in GitHub Desktop.
Save parzibyte/af2efc1394b6d0214041c86516df88ae to your computer and use it in GitHub Desktop.
<?php
/**
* Acortar un enlace utilizando la API de shorte.st
* @author parzibyte
* @see https://parzibyte.me/blog
* @param string $enlace
* @return string|null
* @throws Exception
*/
function acortarConShorteSt($enlace)
{
# Si no tienes, ve a http://join-shortest.com/es/ref/c136c738d9?user-type=new
$claveApi = "AQUÍ_EL_TOKEN_API";
$datos = [
'urlToShorten' => $enlace,
];
$opciones = array(
'http' => array(
'header' => [
"Content-type: application/x-www-form-urlencoded",
"public-api-token: " . $claveApi,
],
'method' => 'PUT',
'content' => http_build_query($datos),
),
);
$contexto = stream_context_create($opciones);
$resultado = @file_get_contents(
'https://api.shorte.st/v1/data/url',
false,
$contexto);
if ($resultado === false) {
throw new Exception("Error al realizar la conexión para acortar $enlace con shorte.st!");
}
$respuestaDecodificada = json_decode($resultado);
if ($respuestaDecodificada->status === "ok") {
$acortado = $respuestaDecodificada->shortenedUrl;
if (preg_match('/^http:\/\/\w+\.com\/\w+$/', $acortado) !== 1) {
throw new Exception("Enlace inesperado al acortar con shorte.st: " . $acortado);
}
return $acortado;
}
throw new Exception(
"Error en la respuesta del servidor al acortar $enlace con shorte.st!"
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment