December 21, 2010 in PHP, Programming, Tutorials by admin

Link shortening websites have been popping up all over the web with the huge explosion in micro blogging requiring a character limit in posts. Sites like bit.ly have become an integral part of twitter in order to maximize the quality of posts. If you are reading this article you probably already know this and just want to know how they are able to shrink down large links and transform them into a very tiny one. We can achieve this with PHP, and the hardest part can be done in just one line of code. Yes it really is that simple.

With just a little bit of php we can convert very large links into something like this:
http://litl.name/f2xoh0/

Using the php function base_convert() we can convert a number into a seemingly random, but far from it, set of upper and lower case characters and numbers. To make a url shortener you could easily take the id from an insert statement into a database and base_convert() the id to get your new url. Using mod_rewrite and .htaccess we could then redirect all traffic excluding our safe pages and use the ending code to look up our url.

Here are a few examples of using base_convert() from 10 base to 36:

echo base_convert(2148, 10, 36);
output: 1no

echo base_convert(9978913, 10, 36);
output: 5xvs1

echo base_convert(9817239871239871, 10, 36);
output: 2onx5qhppkv

echo base_convert(123098809508912480109830971398712398712398739, 10, 36);
output: 4d32xaba8