Search the blog

You should not generate a random password using something like rand() because it is not cryptographically secure. You can use openssl_random_pseudo_bytes() but the problem is it is in hexadecimal and therefore only uses 0–9 and A–F.

If you are using PHP 7+, as you should be, then you can now generate cryptographically secure integers using random_int(). This makes generating a random password easy as I have shown in my example below.

Note that if you cannot use PHP 7+ please visit the following page: PHP 5.x support for random_bytes() and random_int()

function generateSecureRandomPassword($length, $includeSpecialChars = true) {

    if ($includeSpecialChars === true) {

        $chars = [

            '!',
            '"',
            '#',
            '$',
            '%',
            '&',
            "'",
            '(',
            ')',
            '*',
            '+',
            ',',
            '-',
            '.',
            '/',
            ':',
            ';',
            '<',
            '=',
            '>',
            '?',
            '@',
            '[',
            '\\',
            ']',
            '^',
            '_',
            '`',
            '{',
            '|',
            '}',
            '~'

        ];

    } else {

        $chars = [];

    }

    // Add on other characters
    $chars = array_merge($chars, range('a', 'z'), range('A', 'Z'), range(0, 9));

    $count = count($chars) - 1;

    $string = '';

    for ($counter = 1; $counter <= $length; $counter ++) {

        $string .= $chars[random_int(0, $count)];

    }

    return $string;

}

for ($counter = 1; $counter <= 10; $counter ++) {
    
    echo generateSecureRandomPassword(12, false) . PHP_EOL;
    
}

for ($counter = 1; $counter <= 10; $counter ++) {
    
    echo generateSecureRandomPassword(12) . PHP_EOL;
    
}

/*

Sample output:

O1lj3Ej7mZMB
i6KMgCKKyvhF
TSN0SblIxzBo
JOKVBkSYofHh
wZDM5VNjrMxs
vASwXulJWGqt
7IvpxxkFqkWb
sdChVgTyhCV4
UnN43mBmtmDr
7Hr022lA6Xn9
Tk^,0HD/ng&{
!6B&v)[`YyYE
Jl^]yiOvo9=@
>5)Gfi12lktZ
zg['jDzth`:#
!N8yi_$l'l("
j|xx0GB@jIe)
|RV'J$#S83/+
-%vN%KGy\jGB
2!wp2|%k_^eS

*/
Tim Bennett is a Leeds-based web designer from Yorkshire. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.