Simple way to generate a random password in PHP

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…).

13 thoughts on “Simple way to generate a random password in PHP

  1. Replace:
    $password = substr( str_shuffle( $chars ), 0, $length );
    for ($i = 0; $i < $length; $i++) {
    $password .= $chars{mt_rand(0, strlen($chars) – 1)};
    now you've made it quite random.


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

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


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


Leave a Comment

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s