开发者

Random number/letter value

开发者 https://www.devze.com 2023-03-27 06:39 出处:网络
So I was wonder what are some good/preferred methods for generating a \'hex-like\' value in PHP? Preferably, I would want to restrict it to 5 characters long like such: 1e1f7

So I was wonder what are some good/preferred methods for generating a 'hex-like' value in PHP? Preferably, I would want to restrict it to 5 characters long like such: 1e1f7

Currently this is what I am doing:

echo deche开发者_StackOverflowx(mt_rand(10000, 99999));

however this gives me values anywhere from 4-5 characters long, and I want to keep it at a consistent 4 or 5.

What are some ways to better generate something like this in PHP? Is there even a built in function?

Note: When I say 'hex-like' I really just mean a random combination of letters and numbers. There does not have to be a restriction on available letters.


Something simple like:

$length = 5;
$string = "";
while ($length > 0) {
    $string .= dechex(mt_rand(0,15));
    $length -= 1;
}
return $string;

(untested)

Or fix your mt_rand range to: mt_rand(65535, 1048575) (10000-fffff in hex) or if you like tinfoil hats: mt_rand(hexdec("10000"), hexdec("ffffff"))

The advantage of the while-loop approach is that it works for arbitrarily long strings. If you'd want 32 random characters you're well over the integer limit and a single mt_rand will not work.

If you really just want random stuff, I'd propose:

$length = 5;
$string = "";
$characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=+!@#$%^&*()[]"; // change to whatever characters you want
while ($length > 0) {
    $string .= $characters[mt_rand(0,strlen($characters)-1)];
    $length -= 1;
}
return $string;

(untested)


echo substr( base64_encode( mt_rand(1000, mt_getrandmax() ), 0, 5);

This uses more of the alphabet due to the base64, but remember that it will include upper and lower case letters along with numbers.


Why all the work sha1 is tested and evenly distributed:

substr(sha1(uniqid('moreentropyhere')),0,5);

I have used this to generate millions and millions of uniq uids for sharding tables, no collisions and remarkably evenly distributed regardless of the length you use...

you can even use binary form of sha1 hash for base 64:

base64_encode(sha1(uniqid('moreentropyhere'), true))

to limit characters, you can use a regex:

substr(preg_replace('~[^a-km-np-z2-9]~','',strtolower(base64_encode(sha1(uniqid(),true)))),0,6)

Here we limited 0,1,l (letter), and o (letter) from the string, trading a little entropy to prevent confusion (and service tickets) during entry for all ages...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号