How to generate a random password
Short answer
Pick characters from a set with random_int():
<?php
function randomPassword(int $length = 12): string
{
$chars = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$password = '';
for ($i = 0; $i < $length; $i++) {
$password .= $chars[random_int(0, strlen($chars) - 1)];
}
return $password;
}
echo randomPassword();Why not rand() or shuffle()
rand(), mt_rand(), str_shuffle() and shuffle() are predictable. Only random_int() and random_bytes() suit passwords and tokens. The set above has no look-alike characters — 0 and O, 1 and l — so the password is easy to read.
Functions used in this recipe
- random_int — Returns a random integer from a range.
- str_repeat — Repeats a string a given number of times.
- random_bytes — Returns cryptographically secure random bytes.