generate random staring in php code example
Example 1: generate random string in php
function random_str(
int $length = 64,
string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
): string {
if ($length < 1) {
throw new \RangeException("Length must be a positive integer");
}
$pieces = [];
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$pieces []= $keyspace[random_int(0, $max)];
}
return implode('', $pieces);
}
Example 2: Generate Random String in PHP
phpCopy<?php
function secure_random_string($length) {
$rand_string = '';
for($i = 0; $i < $length; $i++) {
$number = random_int(0, 36);
$character = base_convert($number, 10, 36);
$rand_string .= $character;
}
return $rand_string;
}
echo "Sec_Out_1: ",secure_random_string(10),"\n";
echo "Sec_Out_2: ",secure_random_string(10),"\n";
echo "Sec_Out_3: ",secure_random_string(10),"\n";
?>