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

17 Thoughts

  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.

    1. Should be:
      for ($i = 0; $i < $length; $i++) {
      $password .= $chars[mt_rand(0, strlen($chars) – 1)];

  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.

  4. Please do NOT use this example to generate “secure” passwords as the str_shuffle function is based on the insecure, e.g. predictable, rand() or mt_rand() function.

    Please refer to the random_str() function available in php7 or the php5-compatibility functions found here:

    1. Thanks Ronald – this is clearly an old post written long before PHP 7 was even thought of, so thanks for the update there 🙂

  5. 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 Reply