I'm trying to use PHP7's shiny new random_bytes() function to create a 8 and a 12 random character string.
In the official PHP doc there's just an example how to create a hexadecimal string by using bin2hex(). To have greater randomness I would like to generate an alphanumeric [a-zA-Z0-9] string, but couldn't find a way how to achieve this.
Thanks in advance for your help
ninsky
2 Answers 2
Use the ASCII codes of the random bytes as indices into an array (or string) of characters. Something like this:
// The characters we want in the output
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$count = strlen($chars);
// Generate 12 random bytes
$bytes = random_bytes(12);
// Construct the output string
$result = '';
// Split the string of random bytes into individual characters
foreach (str_split($bytes) as $byte) {
// ord($byte) converts the character into an integer between 0 and 255
// ord($byte) % $count wrap it around $chars
$result .= $chars[ord($byte) % $count];
}
// That's all, folks!
echo($result."\n");
Comments
You can use two another approaches. make array from [a-zA-Z0-9], then 1. take 6 or 8 random elements from this array 2. shuffle this array and take 6 or 8 elements from start or from any part of array
<?php
$small_letters = range('a', 'z');
$big_letters = range('A', 'Z');
$digits = range (0, 9);
$res = array_merge($small_letters, $big_letters, $digits);
$c = count($res);
// first variant
$random_string_lenght = 8;
$random_string = '';
for ($i = 0; $i < $random_string_lenght; $i++)
{
$random_string .= $res[random_int(0, $c - 1)];
}
echo 'first variant result ', $random_string, "\n";
// second variand
shuffle($res);
$random_string = implode(array_slice($res, 0, $random_string_lenght));
echo 'second variant result ', $random_string, "\n";
random_bytes()isn't designed to restrict its range of bytes to a subset of the ASCII character set? This isn't really the appropriate function for hat you want to dorandom_bytes()is designed to be cryptographically secure. Basically as good as it gets on standard hardware. It might look like you are doing better but you have actually just shot yourself in the foot.Random::alphanumericString($length)seems to be what you want.