Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert MD5 to base62 for URL

Tags:

php

md5

base62

I have a script to convert to base 62 (A-Za-z0-9) but how do I get a number out of MD5?

I have read in many places that because the number from an MD5 is bigger than php can handle as an integer it will be inaccurate... As I want a short URL anyway and was not planning on using the whole hash, maybe just 8 characters of it....

So my question is how to get part of the number of an MD5 hash?

Also is it a bad idea to use only part of the MD5 hash?

like image 353
Mark Avatar asked Dec 10 '09 10:12

Mark


1 Answers

I'm going to suggest a different thing here.. Since you are only interested in using a decimal chunk of the md5 hash why don't you use any other short numeric hash like CRC32 or Adler? Here is an example:

$hash = sprintf('%u', crc32('your string here'));

This will produce a 8 digit hash of your string.

EDIT: I think I misunderstood you, here are some functions that provide conversions to and from bases up to 62.

EDIT (Again): To work with arbitrary length numbers you must use either the bc_math or the GMP extension, here is a function that uses the bc_math extension and can also convert from base 2 up to base 62. You should use it like this:

echo bc_base_convert(md5('your url here'), 16, 62); // public base 62 hash

and the inverse:

echo bc_base_convert('base 62 encoded value here', 62, 16); // private md5 hash

Hope it helps. =)

like image 155
Alix Axel Avatar answered Sep 27 '22 18:09

Alix Axel