PHP - Generate an 8 character hash from an integer

29,454

Solution 1

Why don't you just run md5 and take the first 8 characters?

Because you are wanting a hash, it doesn't matter whether portions are discarded, but rather that the same input will produce the same hash.

$hash = substr(md5($num), 0, 8);

Solution 2

>>> math.exp(math.log(40000)/8)
3.7606030930863934

Therefore you need 4 digit-symbols to produce a 8-character hash from 40000:

sprintf("%08s", base_convert($n, 10, 4))

Solution 3

For php:

$seed = 'JvKnrQWPsThuJteNQAuH';
$hash = sha1(uniqid($seed . mt_rand(), true));

# To get a shorter version of the hash, just use substr
$hash = substr($hash, 0, 10);

http://snipplr.com/view.php?codeview&id=20236

Share:
29,454
doc
Author by

doc

I got my first Stack Overflow the other day, it was like a badge of honour.

Updated on July 12, 2022

Comments

  • doc
    doc almost 2 years

    Is there a way to take any number, from say, 1 to 40000 and generate an 8 character hash?

    I was thinking of using base_convert but couldn't figure out a way to force it to be an 8 character hash.

    Any help would be appreciated!