Last active
October 31, 2019 02:15
-
-
Save parzibyte/af2efc1394b6d0214041c86516df88ae to your computer and use it in GitHub Desktop.
Use shorte.st API with PHP | https://parzibyte.me/blog/2019/10/30/acortar-enlace-shorte-st-php/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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