Convert MD5 to base62 for URL

前端 未结 9 459
再見小時候
再見小時候 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:27

    If it's possible, I'd advise not using a hash for your URLs. Eventually you'll run into collisions... especially if you're truncating the hash. If you go ahead and implement an id-based system where each item has a unique ID, there will be far fewer headaches. The first item will be 1, the second'll be 2, etc---if you're using MySQL, just throw in an autoincrement column.

    To make a short id:

    //the basic example
    $sid = base_convert($id, 10, 36);
    
    //if you're going to be needing 64 bit numbers converted 
    //on a 32 bit machine, use this instead
    $sid = gmp_strval(gmp_init($id, 10), 36);
    

    To make a short id back into the base-10 id:

    //the basic example
    $id = base_convert($id, 36, 10);
    
    //if you're going to be needing 64 bit numbers
    //on a 32 bit machine, use this instead
    $id = gmp_strval(gmp_init($shortid, 36));
    

    Hope this helps!

    If you're truly wanting base 62 (which can't be done with gmp or base_convert), check this out: http://snipplr.com/view/22246/base62-encode--decode/

提交回复
热议问题