Creating Short URLs With PHP and the TinyURL API

| Comments

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, 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:**[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 = "" . $url; $tinyurl = file_get_contents($url); return $tinyurl; }

Simple, n’est ce pas?


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

Da da! Your very own link!