About Me
Latest Tweet
- Interesting article about Twitter's (poor) OAuth implementation - http://t.co/9jc153p 4 hours ago
-
Recent Posts
- Links for 7th April, 2010
- Links for 31st March 2010
- Privacy by obscurity
- Are Apple making a play to cripple Google/Microsoft?
- RE: Is Facebook unethical, clueless or unlucky?
- Mindset of the mob – a response to John Waters
- Kevin Smith, Dublin, October 14th
- Base-56 Integer Encoding in PHP
- Bolshevik Bingo!
- Irish URL shortening services
Recent Comments
Categories
Development
Recreational
Technology
Base-56 Integer Encoding in PHP
I found myself needing to write a URL-shortening system recently, nothing particularly fancy, just something that would result in URLs similar to those of tinyURL and bit.ly. PHP’s own base64 function is purely for encoding string data to make it “URL safe” and actually results in a longer string. PHP also has a base_convert function, but this only goes up to base-36, and it seemed like a waste to only go as far as base-36 when more can be fit in.
I found a couple of functions written in Python on StackOverflow for base-62 conversion that solved the problem perfectly. The author of the solution, Baishampayan Ghose, also suggested a shorter alphabet (removing similar characters for ease of readability) which would whittle it down to base-56. I’ve ported the functions to PHP and employed a base-56 alphabet in the example below, but it would be trivial to swap it out for a longer one if required.
Usual code-usage caveats apply.