PHP Random String Generator
Published 5 years ago.
Last updated
/**
* Generate a random string, using a cryptographically secure
* pseudorandom number generator (random_int)
*
* per https://stackoverflow.com/a/31107425
*/
function get_random_string($length = 16, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
// Tests.
echo 'Test 01: ' . get_random_string() . "\n";
echo 'Test 02: ' . get_random_string(2) . "\n";
echo 'Test 03: ' . get_random_string(32) . "\n";
echo 'Test 04: ' . get_random_string(16, '1234567') . "\n";
echo 'Test 05: ' . get_random_string(16, '123abcABC') . "\n";
echo 'Test 06: ' . get_random_string(16, 'ABC') . "\n";
echo 'Test 07: ' . get_random_string(16, '10') . "\n";