Pezholio

18 Mar, 2009

Creating short URLs with PHP and the TinyURL API

Posted by: Pez In: Web Development

With the increasing popularity of Twitter and the like, it’s becoming more and more important to keep those characters down with URL shortening services such as is.gd, cli.gs and of course, the ubiquitous TinyURL

A lot of these services offer APIs, taking a long url and returning the short url. But a lot of these are returned in JSON or XML format, meaning that you have to use a lot of extra time and processing power parsing the output to get the URL, and if you want to do that a lot of times, that’s a whole lot of extra strain on your server.

However, TinyURL has an ace up it’s sleeve, a (as far as I can see) undocumented API, which adheres the the principle of KISS design. It just returns your shortened URL in plain text. The format is as follows:

http://tinyurl.com/api-create.php?url=[URL here]

We can then have a nice simple PHP function that takes our URL as the input and returns the TinyURL like so:


function tinyurl($url) {
$url = "http://tinyurl.com/api-create.php?url=" . $url;
$tinyurl = file_get_contents($url);
return $tinyurl;
}

Simple, n’est ce pas?

Update

I’ve just noticed that is.gd offer a similarly simple API, so to get an even shorter URL, simply replace the tinyurl element with:

http://is.gd/api.php?longurl=

Da da! Your very own is.gd link!

5 Responses to "Creating short URLs with PHP and the TinyURL API"

2 | Native

May 27th, 2009 at 8:53 am

Avatar

I want to soap to create shorter URLs and I am currently looking at using the service provided at 101.gs – there is an example soap call at http://101.gs/apiexample.php – do I need nusoap or can I use the native php soap?

3 | Pez

May 27th, 2009 at 9:07 am

Avatar

I’ve never touched SOAP to be honest, but I’d give it a try with the native PHP soap first, if no joy, try nusoap. There are ways and means round these things, so you might not even need to use either.

4 | dan

August 10th, 2009 at 6:03 am

Avatar

Thank you for the example.

What if:

I need to make shorter multiple links. All that i need is a shorter url for each.

Do you have any clue ?

thank you.

5 | Pez

August 10th, 2009 at 11:52 am

Avatar

Hi Dan,

That would be pretty simple to sort I reckon. Just stick the urls you want into an array like so:


$links = array('http://www.link1.com','http://www.link2.com','http://www.link3.com','http://www.link4.com');

And then loop through the array, applying the function to each link like so:


foreach ($links as $link) {
$short[] = tinyurl($link);
}

You’ll then be able to access each link via $short[0], $short[1], $short[2] etc.

Hope this helps!

Comment Form

Twitter / @pezholio



Desperate monetisation attempt…