How URL shortening works

What is URL shortening ?
URL Shortening service reduces the length of a URL.
You can see the current webpage Long URL:http://hayageek.com/how-url-shortener-works/ and the webpage can be accessed using the short URL:http://hayageek.com/?p=59

How URL shortening works ?
Long URL is inserted to Database table,  where 59 is the corresponding Row ID for the long URL.  When  ?p=59 is accessed, page is redirected to the corresponding long URL  using  HTTP 301 method.

If you want to make a URL shortening service, Your system should be capable of storing many URLs.
What happens when the number of URLs inserted in to database are more and the Row ID becomes very big(ex:123456789089898) ? How it can be shortened. ?

Before going to the main shortening algorithm, you need to understand Decimal to Hex Conversion(Bas6 16).

1.Base 16 (Hex Decimal)
Everybody knows about Decimal (10) to Hex(16) conversion. Below is the mapping table for Decimal to Hex.
Characters Used: “0123456789ABCDEF”

Decimal123456789101112131415
Hex123456789ABCDEF

How to Convert Decimal number to Hex

Video

So 123456789089898 is represented as 7048860F0E6A in Hex. Length of the number is shortened by 3 characters

2.Base 36
Base16, ends at ‘F’.  But in Base 36 algorithm ,10 digits(0-9) +26 alphabets (A-Z) are used. Below is the Base36 look-up table.
Characters Used: “0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ”

 Decimal123456789101112131415161718
 Base 36123456789ABCDEFGHI
Decimal
1920212223242526272829303132333435
Base 36JKLMNOPQRSTUVWXYZ

123456789089898 is represented as 17RF9KNWX6 . Length is shortened by 5 characters.

3.Base 62  Conversion:
Many of the URL shortening services use Base 62 algorithm. In Base 62,  10 digits + 26 characters (a-z) + 26 characters(A-Z) are used.
Characters Used: “0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”

123456789089898 is represented as : z3wBX5. Length is shortened by 9 characters.

So using Base62 algorithm, length of any number can be reduced significantly.

PHP Code for Base62: http://ideone.com/HOwl79


I am a Developer. My motto: "Language is not a barrier" http://hayageek.com
All posts by Ravishanker Kusuma