I'm looking to create a reusable function that will generate a random key with printable ACSII characters of chosen length (anywhere from 2 to 1000+). I'm thinking printable ASCII characters would be 33-126. They key does not need to be completely unique, just unique if generated at the exact same millisecond (so uniqid()
won't work).
I'm thinking a combination of chr()
and mt_rand()
might work.
Is this the way to go, or is something else the best method?
Edit: uniqid()
will also not work because it doesn't have a length parameter, it's just whatever PHP gives you.
My Idea: This is what I came up with:
function GenerateKey($length = 16) {
$key = '';
for($i = 0; $i < $length; $i ++) {
$key .= chr(mt_rand(33, 126));
}
return $key;
}
Are there any problems with this?
Another Edit: Most of the other questions deal with password generation. I want a wider variety of characters and I don't care about 1
vs l
. I want the maximum number of possible keys to be possible.
Note: the generated key does not necessarily have to be cryptographically secure.
Random::asciiPrintableString($length)
does exactly what you need. If you only want letters and numbers, useRandom::alphanumericString($length)
instead. – Caren