Get a shortened URI with TinyURL API and cURL
Many times in my application I need to create a shortened URI. There are many websites with free API that can do it for you: tinyurl.com, tr.im and others. Here’s how to do it with both TinyURL and tr.im:
TinyURL
-
$uri = 'http://blog.richardknop.com/';
-
$ch = curl_init();
-
curl_setopt($ch, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url=' . $uri);
-
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
-
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
-
$tinyUri = curl_exec($ch);
-
curl_close($ch);
-
-
// let's echo the tiny URI
-
echo $tinyUri;
tr.im
-
$uri = urlencode('http://blog.richardknop.com/');
-
$ch = curl_init();
-
curl_setopt($ch, CURLOPT_URL, 'http://api.tr.im/api/trim_url.json?url=' . $uri);
-
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
-
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
-
$json = curl_exec($ch);
-
$tinyUri = json_decode($json)->url;
-
curl_close($ch);
-
-
// let's echo the tiny URI
-
echo $tinyUri;
