How to generate a random string
Short answer
random_bytes() gives random bytes, bin2hex() turns them into text:
<?php
echo bin2hex(random_bytes(8));Your own character set
Pick the characters one at a time with random_int():
<?php
function randomString(int $length): string
{
$alphabet = 'abcdefghjkmnpqrstuvwxyz23456789';
$result = '';
for ($i = 0; $i < $length; $i++) {
$result .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
return $result;
}
echo strlen(randomString(10));Output:
10A numeric code
A six-digit confirmation code with leading zeros:
<?php
echo str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);Functions used in this recipe
- random_bytes — Returns cryptographically secure random bytes.
- random_int — Returns a random integer from a range.
- uniqid — Returns an identifier based on the current time.