Reputation: 371
I am working on a site that requires people to type the ID of a user after the URL to get to the page they need. E.g. www.mysite.com/235163 where 235163 is the ID number of the profile. But is there a way to shorten numbers by introducing alpha numeric characters into the ID number so 235163 may be shortened to 1d or something a long that lines as obviously, i'm merely trying to minimize mistakes from the user inputting long numbers. Can anyone help?
Upvotes: 1
Views: 1109
Reputation: 5008
I recently encountered a similar challenge; my solution was to convert the base-10 number (decimal) into base-64. Base-64 uses other characters (A-Z, a-z, etc) to represent the number; this effectively reduces the number of characters needed to represent the number. This "shortened number" can then be used in the URL.
For PHP, Paul Greg created some code that handles converting from base-10 to another base. I also blogged about converting row ID's to Base-64 for short url's on my personal blog. However, my code utilizes C#; if you're interested in using this approach then use Paul's code to recreate this for PHP.
Upvotes: 1
Reputation: 684
This first thing that springs to mind is to use dechex() to convert from decimal into hexadecimal, so in this case 235163 would become 3969b, and obviously very easy to translate back to the id using hexdec()
echo hexdec(235163); // 3969b
echo dechex('3969b') // 235163
Or you could use base_convert() to convert to base 36, giving:
echo base_convert(235163, 10, 36); // 51gb
echo base_convert('51gb', 36, 10); // 235163
Upvotes: 2