How to shorten URL using TinyUrl service

H

Many times clients are asking me to shorten their URLs within application. So I created a very simple but effective function that is calling TinyUrl web service using PHP curl.

The best thing is that this code snippet can be used to call any similar web service. And this is a great example how we can use curl functions to remotely call web services or get some data from other sites.

So please feel free to use it anyway you see fit.

And here is the code:

function fetchTinyUrl($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.''; 
}

Let me explain. Curl is a set of functions in PHP used to connect and communicate to many different types of servers with many different types of protocols.

curl_init initializes a new session and return a cURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions. You can set various options using curl_setopt. CURLOPT_URL is setting the URL, we are setting CURLOPT_RETURNTRANSFER to true (1) and telling cURL to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly. CURL_CONNECTTIMEOUT is the number of seconds to wait while trying to connect.

$data is the variable holding the return string after curl_exec() is done with its magic. Last but not least, always close a cURL session and free all resources.

This function is creating and executing a curl call to http://tinyurl.com/api-create.php and giving it a GET parameter with long url value. It simply returns a hyperlink with shortened URL.

About the author

Zvonko Biškup

A passionate web developer with more than 13 years experience in PHP and other web related technology. My main interest is WordPress and new PHP frameworks.
Owner of Influendo Programming.
Enjoys exploring new stuff and possibilities, using new technologies and just having fun developing awesome stuff.

  • Sandy

    Nice posting! I generally use URL shortening services like bit.ly, aafter.com and goo.gl.

Tags