Convert MD5 to base62 for URL

前端 未结 9 513
再見小時候
再見小時候 2020-12-30 10:43

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

9条回答
  •  再見小時候
    2020-12-30 11:24

    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. =)

提交回复
热议问题