Php – How to generate URLs for a custom URL shortener

database-designMySQLPHPurl

Due to some issues with other shorteners like goo.gl (disabling my links for example) I want to create my own URL shortener.

I am looking to have a single table that will contain the following columns :-

links_id - autoincrement id
url - the actual full URL
abbreviation - the shortened version 

In a nutshell, when a new link is added to the table, I will insert the URL into the table and give this a unique abbreviated value, obviously if an existing URL is found it won't need to re-add the URL.

My question is what is the best way to generate such abbreviations that are fast to produce and are as unique as possible and not simple to guess. In addition how many number of characters would people recommend, for instance, if I had an abbreviation of 6 characters, how many unique combinations would this provide me based I am using the standard characters as used by other URL shorteners.

I will be using PHP/MySQL, any advice would be appreciated.

Best Answer

URL shortners do not use hashes to generate the shortened URL. Hashes are not (by their very design) unique.

A common way to encode URLs is to simply take the links_id value and convert it to base 62 (ie a-z, A-Z and 0-9, giving 62 values per "digit") and use that as the URL.