When creating web apps, there’s often a need to generate a random password for your users. There are a number of ways to do this, but in needing to do it recently I came up with this very simple function that will generate a password (or other random string) of whatever length you wish. It’s particularly useful when generating passwords for users that they will then change in the future. It uses PHP’s handy str_shuffle() function:

The only shortcoming of this method will come in when you want to generate a password that is longer than $chars, but this is rather unlikely I would think. Also, the fact that it will only ever use each character a maximum of one time means that it is more susceptible to a brute force attack (whether that’s a problem or not depends on how paranoid you are…).


  1. If you want to have a password with repeating chars:

    $password = substr ( str_shuffle ( str_repeat ( $chars ,$length ) ), 0, $length );


  2. I believe this algorithm is highly insecure as str_shuffle uses a very predictable randomness and was not made to be used for nearly cryptographic uses.


  3. Hi,
    I’ve added a bit more “randomness”, respectively have added some stuff to make up for the lack of randomness in PHP 5 (still commonly used). In short:

    – created random seed
    – create random offset in substr
    – add loop while certain password complexity conditions aren’t met

    function random_password( $length = 8 ) {
    $chars = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?”;
    $password = ”;
    while(preg_match(‘/[a-z]/’,$password) == 0 && preg_match(‘/[A-Z]/’,$password) == 0 && preg_match(‘/[0-9]/’,$password) == 0 && preg_match(‘/[\!\@\#\$\%\^\&\*\(\)\_\-\=\+\;\:\,\.\?]/’,$password) == 0) {
    $password = substr( str_shuffle( $chars ), mt_rand(0,strlen($chars)-1), $length );
    return $password;


Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s