Laravel Str Generate a more truly "random" alpha-numeric string.
public static function random($length = 16)
{
$string = '';
while (($len = strlen($string)) < $length) {
$size = $length - $len;
$bytes = random_bytes($size);
$string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
}
return $string;
}
Example
- cryptographically secure random alphanumeric string that utilizes all characters from a to z
- random_bytes() only make use of hexadecimal character
function secure_random_string($length) {
$random_string = '';
for($i = 0; $i < $length; $i++) {
$number = random_int(0, 36);
$character = base_convert($number, 10, 36);
$random_string .= $character;
}
return $random_string;
}
// Output: 07y1s10prb8
echo secure_random_string(10);
// Output: d9bcwoo7pc
echo secure_random_string(10);
// Output: 6llfxe4pvm
echo secure_random_string(10);