PHP Passwords with Character Arrays

P

Here’s a simple function I recently wrote to randomly generate passwords in PHP.

//Generate new password
$characterPool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-_+=:;<>?';
$newPassword = '';
while(strlen($newPassword)<8)
    $newPassword .= $characterPool[mt_rand(0,strlen($characterPool)-1)];

Simplified a bit, this is equivalent to:

//Generate new password
$characterPool = 'abcdefghijklmnopqrstuvwxyz';
$characterPool .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$characterPool .= '1234567890';
$characterPool .= '!@#$%^&*()-_+=:;<>?';
$newPassword = '';
while(strlen($newPassword) < 8){
    $index = mt_rand(0,80);  //81 characters in 0-indexed pool
    $newPassword = $newPassword . $charcterPool[$index];
}

This works because like C, PHP allows a string to be accessed as an array of characters using either brackets or braces:

$myString = ‘Hello World.’;
echo $myString[0]; //displays H
echo $myString{1}; //displays e

Note: Curly brace syntax was deprecated as of PHP 7.4 and no longer supported as of PHP 8.0.

For 8-character passwords the algorithm above will produce a string containing at least three of the four character types (upper case, lower case , digits and symbols) more than 99.9% of the time. This can be shown by removing from the set of all possible passwords those passwords that contain only one of the four character types.

All possible passwords: (26+26+10+19)8 = 818
Passwords containing only lower case characters: 268
Passwords containing only upper case characters: 268
Passwords containing only digits: 108
Passwords containing only symbols: 198

P=\frac{81^8-(26^8+26^8+10^8+19^8)}{81^8} = 1-\frac{26^8+26^8+10^8+19^8}{81^8} = .999765\ldots

This comports with the results of a run of 10,000,000 samples which yielded 9,997,635 passwords containing characters from at least two groups.

Note that this article is meant as a demonstration of one way to quickly generate general purpose passwords. If you need to generate highly secure passwords you will need to do more homework, including but not limited to replacing the mt_rand function with a cryptographically secure PRNG.

About the author

Chris Peterson

As a Web Application Developer & Elephant Trainer I have been putting the PHP mascot to work for more than a decade. I specialize in back-end development and use the LAMP stack to craft software that frees human beings to spend their time on more productive and rewarding things.

1 comment

By Chris Peterson

Chris Peterson

As a Web Application Developer & Elephant Trainer I have been putting the PHP mascot to work for more than a decade. I specialize in back-end development and use the LAMP stack to craft software that frees human beings to spend their time on more productive and rewarding things.

Recent Posts

Recent Comments

Archives