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: and the webpage can be accessed using the short URL:

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”


How to Convert Decimal number to Hex


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.

 Base 36123456789ABCDEFGHI

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:

About Author

I am a developer and I maintain the site The best software developers are those who can think like both a developer and a user.
All posts by Ravishanker Kusuma