Jun 30 / Richard Knop

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

  1. $uri = 'http://blog.richardknop.com/';
  2. $ch = curl_init();
  3. curl_setopt($ch, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url=' . $uri);
  4. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  5. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  6. $tinyUri = curl_exec($ch);
  7. curl_close($ch);
  8.  
  9. // let's echo the tiny URI
  10. echo $tinyUri;

tr.im

  1. $uri = urlencode('http://blog.richardknop.com/');
  2. $ch = curl_init();
  3. curl_setopt($ch, CURLOPT_URL, 'http://api.tr.im/api/trim_url.json?url=' . $uri);
  4. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  5. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  6. $json = curl_exec($ch);
  7. $tinyUri = json_decode($json)->url;
  8. curl_close($ch);
  9.  
  10. // let's echo the tiny URI
  11. echo $tinyUri;
Leave a Comment