php

Create a TinyURL with PHP

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.

//gets the data from a URL
function get_tiny_url($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);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

//test it out!
$new_url = get_tiny_url('http://www.paktutorial.com/php-articles/create-a-tinyurl-with-php');

//returns http://tinyurl.com/3zpq9gx
echo $new_url;

Simply provide the URL and you’ll received the new, tiny URL in return.

DOWNLOAD SOLUTION HERE