PHP Passwords with Character Arrays

P

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

Simplified a bit, this is equivalent to:

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

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
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

Time limit is exhausted. Please reload the CAPTCHA.

Chris Peterson By Chris Peterson

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