Let’s supose you want to develop your own URL shortener, like Bit.ly for example.
You can, of course, use the ID as a integer, like, 1, 2, 3, etc. If you have 12.345 rows in your database table, you will need 5 digits, like http://example.com/12345. Large applications like Youtube, have much more entries, so, to use numbers, the URL will be very long, like
Because that, these websites, like YouTube, t.co, bitly.com or even vine.co, are using a generated ID using uppercase letters, lowercase letters, digits and sometimes underscore (_) and hyphen (-). You can check that given a YouTube video URL where you will find something like
http://www.youtube.com/watch?v=2Z4m4lnjxkY. You can see they’re using the “2Z4m4lnjxkY” as ID.
The Math – Base 10
You have the ID in pure digits (base 10, or decimal), where you have 10 options for each “position”: 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. So, with 5 positions you can theoretically represent 10*10*10*10*10 (100.000) IDs. Of course you won’t represent the number 45 as 00045 or even will have the 00000 ID, but they are mathematics options. 😀
So, to improve the number of options you can add more chars, like lowercase letter and digits. Basically you can use a base32 converter. The base32 will convert a decimal number to a string using digits and lowercase letters, like
<?php // Converting the number 328743826 from base 10 to base 32 echo base_convert(328743826, 10, 32);
This will produce the result “9pgesi”. Cool, we could reduce a lot the number of characters. But we can do better.
With base32 you have all digits and all lowercase letters. With base62 we have also uppercase letters, generating IDs like “8H9j8sD79”. So using a base62 convertor we have much more options than base32. For example, with 5 positions we can have 62*62*62*62*62 = 916.132.832 options.
With PHP you cannot use the
base_convert function because it only works from base 2 to base 36 and we need more, we need 62, so we have some already coded sources to do that.
This is how you can use this class to generate your base62 strings:
<?php $my_id = 23435; // get the ID from MySQL for example; $base62 = Math::to_base($my_id, 62);
To get the decimal ID from the base62 string you have to do:
<?php $base62 = 'b6H8Jk2'; $decimal = Math::to_base_10($base62, 62);
You must add a new column on your database table called, for example, “base62”. So every time you insert a new item you get the ID, generate the base62 string and save.