Reputation: 55
I am trying to create a function which creates a random String. This String should consist of letters (only caps) and numbers. It will be used to activate a product. So the user has to type it into a text field. So far I found the following function:
function random_str($length, $keyspace = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'){
$pieces = [];
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$pieces []= $keyspace[random_int(0, $max)];
}
return implode('', $pieces);
}
I do not have that much experience with random functions. So is there anything to improve or would you suggest a different function?
Upvotes: 0
Views: 293
Reputation: 59
readable - base64_encode(random_bytes($lenght ) ); shorter
readable longer - bin2hex(random_bytes($lenght ) );
To make with wanted length use substr
Upvotes: 0
Reputation: 76
To generate a cryptographically secure random string (which I would recommend for an activation key), I would rather use openssl_random_pseudo_bytes
You can find the doc here and some useful informations in that thread (for example, how to get a random string with 0-9A-Z characters rather than just 0-9A-F).
As of PHP7.0 you could also use random_bytes, which is also cryptographically secure.
Upvotes: 2
Reputation: 146
Use rand function instead of 'random_int'
function random_str($length, $keyspace =
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'){
$pieces = [];
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$pieces []= $keyspace[rand(0, $max)];
}
return implode('', $pieces);
}
echo random_str('50');
// Output //
P7V55MYPQJGRNQ8W0VW7TRKBDK2B7NXWUT20F0P6J5Y7W63X20
Upvotes: -1