Short Url with TinyUrl API and PHP

TinyURL is an awesome service allows you to take a long URL like “http://seobat.net/wordpress/wordpress-faster-than-ever-with-wp-supercache” and turn it into a shorter one “http://tinyurl.com/lvogdo”. Using PHP and TinyURL API, you can create these tiny URLs on-the-fly. The API call is very simple, you have to fetch “http://tinyurl.com/api-create.php?url=YOUR_URL_HERE” where instead of YOUR_URL_HERE you have to put the URL to be shorted.There are two ways to achieve this goal in PHP:

  1. Using cURL
  2. Using file_get_contents PHP function

Version 1 using cURL

// Define the function to get the data from TinyUrl
 
function get_tiny_url($url)
{
    $ch = curl_init(); // Init cURL lib
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, "http://tinyurl.com/api-create.php?url=$url"); // Set the url to be fetched
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // Set cURL timeout
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Disable print out
    $data = curl_exec($ch); // Exec
    curl_close($ch); // Close
    return $data; //Return shorted URL
}
 
// Test Usage
 
$long_url = "http://seobat.net/wordpress/wordpress-faster-than-ever-with-wp-supercache";
$short_url = get_tiny_url($long_url); // Getting short URL from long URL
 
echo "Short URL is $new_url"; // Print the short url, in this case “Short URL is http://tinyurl.com/lvogdo”




Version 2 using file_get_contents PHP function

// Define the function to get the data from TinyUrl
 
function get_tiny_url($url)
{
    return file_get_contents("http://tinyurl.com/api-create.php?url=$url");
}
 
// Test Usage
 
$long_url = "http://seobat.net/wordpress/wordpress-faster-than-ever-with-wp-supercache";
$short_url = get_tiny_url($long_url); // Getting short URL from long URL
 
echo "Short URL is $new_url"; // Print the short url, in this case “Short URL is http://tinyurl.com/lvogdo”

Enjoy!

Related links:



Stumble
Delicious
Technorati
Twitter
Facebook




Social tagging: > > > > >


  1. Kevin on Wednesday 8, 2009

    Thanks for nice post ^^

  2. TinyURL on Wednesday 8, 2009

    TinyURL has experienced shrinkage in US traffic in the past month. Its API is a good feature but tinyurl needs to improve more in terms of its user interface.