**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”

Decimal | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |

Hex | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |

**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.

Characters Used: “0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ”

Decimal |
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |

Base 36 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F | G | H | I |

Decimal |
19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 |

Base 36 | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z |

**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