Monday, February 23, 2009

TinyURL with one line of PHP? Easy!

Everyday we learn something new. For programmers it's especially important so that we don't sour and stink like a month-old milk.

Yesterday I was looking for a better (read cleverer) solutions to build a TinyURL analog. Everyone find his own need to build such a service, I needed it to be able to share URLs in SMS (text messages), track usage and statistics and be independent from 3rd party solutions such as (one rule I learned at my job - you can't rely on anyone - even google may go down while you're up and your service should not be interrupted).

So saying that much I'm pushing away the solution which is really one line of PHP! To convert URL to it's short representation you need:
$short_url = base_convert($url_id, 10, 36);
To convert short URL to it's original you will need:
$url_id = base_convert($short_url, 36, 10);
This will return a numeric id of the long URL stored in the DB with following structure:
`id` int(11) NOT NULL auto_increment,
`url` text NOT NULL,
Obviously you will need little bit more lines of code to provide some type of interface for your application, but it's main part is done by magic of base_convert() function which converts regular decimal number (base 10) to base 36 which uses letters of English alphabet as additional digits.

And if you are so lazy that you can't even think about writing your own application utilizing provided function or you trully believe in Open Source - I also found a full listing of such application for you.

No comments:

Post a Comment

Please be moderate saying your thoughts and do not offend others.