Create a TinyURL using PHP and TinyURL API

TinyURL is an awesome service. For those who don’t know what TinyURL is, TinyURL allows you to convert your long URLs like “http://www.akchauhan.com/category/jquery/” to small URLs like “http://tinyurl.com/yz4c4ba”. Basically you need such type of service when you are posting your data to some third party web service and there is limit on the number of characters you can post like Twitter. Twitter only allow 140 characters long Tweet.

Using the PHP and TinyURL API, you can create these tiny URLs.

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.akchauhan.com/category/jquery/');
 
//returns http://tinyurl.com/yz4c4ba
echo $new_url;

,


  1. #1 by Andriy Kopachevskiy - November 24th, 2009 at 15:18

    Hi, I didn’t know that tiniurl not require secret keys like bit.ly does.

    by the way, what module do you use to output such nice php code formatting on your blog?

  2. #2 by admin - November 24th, 2009 at 15:25

    @Andriy Kopachevskiy
    Hi Andriy,
    I’m using WP-Syntax (http://wordpress.org/extend/plugins/wp-syntax/) module for code formatting.

  3. #3 by giulio - December 29th, 2009 at 23:52

    Hi, I’ve found the same function with the file_get_contents method. And I’ve made a reverse function to get the long url back using CURL library here:
    http://www.barattalo.it/2009/12/29/tiny-url-encode-and-decode-with-php/
    bye
    Giulio

(will not be published)

 


Submit Comment
Subscribe to comments feed