Using tinyurl.com api calls for shortening long urls

TinyURL is a url shortener service or you may also call it a url crusher service, which takes in long urls and converts them into very short urls. With the increasing popularity of Twitter and a limitation of 140 characters on tweets, the url shortening services have gained popularity over the past few years. There are over 100+ url shortening services now at a user’s disposal.

Almost all such services provides an option for developers to make api calls to return a short url given a long url but they also require an account and an API key. However, tinyurl.com doesn’t require the user to have an account or an api key.

All one has to do is include the following function into a function.php file which you can include in any other php file where you need to make a call to tinyurl API.

<?php
 function shortURL($url) {
 $ch = curl_init();
 $timeout = 5;
 curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url);
 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
 curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
 $short_url = curl_exec($ch);
 curl_close($ch);
 return $short_url;
 }
 ?>

To get the short url for a long url, one has to simply call this function as below:

$url = "http://technoflirt.com/tech/2011/01/11/running-php-script-host/";
 $short_url = shortURL($url);
 echo "Actual url =". $url . "<br />";
 echo "Shortened url = <a href=$short_url>$short_url</a>  <br />";

One can also observe how the short url link gets hyperlinked in the last statement.  However, tinyurl.com itself occupies quite a few characters compared to other services such as bit.ly, go.af etc. , so other services are now often used in comparison. The advantage is that it doesn’t have a rate limit in the API calls as bit.ly and others.

Leave a Reply

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.