I needed to generate a unique code, suitable for URLs and somewhat short so it doesn’t scare the user.
Doing md5(microtime()) is nice but it is 32 chars long. I could use base64, but it contains weird characters like "/" and "=".
So how do I restrain the encoding to alphanumeric ? I found the inspiration from Ross Duggan and I added a random function. He also removes a couple ambiguous chars, which I think is a nice touch.
The choice of random could be discussed but the idea is there.
UPDATE: As suggested by a friend, it is simpler and a better use of the range of available entropy to generate each character separately. You can see the old version in the Gist.
Tests included
No comments:
Post a Comment