Generate random password with limited length

With the following PHP snippet you can generate simple and secure passwords (without coding). Specifically, I am going to show you one. php function so you can reuse the code in your developments.

You can use these passwords personally or so that your applications generate random and secure passwords for your users.

Content

  • Function to generate simple random strong passwords
  • Guidelines for generating strong passwords
  • Function to generate very secure passwords
  • Conclusion for getting strong passwords in PHP

Function to generate simple random strong passwords

function password_random( $length=6 ){
 
    //palabras y caracteres que se utilizarán para crear la contraseña
    $words = 'perro, gato, musica, amigo, aprender, php, javascript, ada, lovelace, codigo, js,';
    $words .= '!,?,.,¡,?,_,';
    $words .= 'A,B,C,D,E,J,H,K,Z,P,U,W,';
 
    // partimos las cadenas por las comas:
    $array_words = explode(',', $words);
 
    // Añade palabras mientras la contraseña es más corta de lo requerido
    $pwd = '';
    while ( strlen($pwd) < $length ){
        $r = mt_rand(0, sizeof( $array_words )-1);
        $pwd .= $array_words[$r];
    }
 
    // añade un número al final si el password es mayor que 2
    // reduce además el password a la longitud especificada en $length
    $num = mt_rand(1, 99);
    if ($length > 2){
        $pwd = substr( $pwd, 0, $length - strlen($num) ) . $num;
    } else { 
        $pwd = substr( $pwd, 0, $length );
    }
 
    return $pwd;
 
}

Guidelines for generating strong passwords

This function is intended to get easy passwords, that is, short and easy to memorize, as well as safe. Although to a large extent the strength of the generated password will depend on the length, the combination of different characters, upper and lower case letters, symbols and numbers achieve the desired security.

Now it is up to you to generate more or less secure passwords depending on the length of the password that you indicate as the input parameter of the function ($length) and with the terms and characters that you enter in the variable $words.

If what you are looking for is to achieve a high level of security for the passwords you generate, I recommend you modify the function as follows:

  1. Use a minimum of 10 characters for character length.
  2. In the first row of words of the variable $words introduce unusual words. For this you can use a dictionary to find strange and rarely used words.
  3. Add, in the second row of the variable $words more symbols and characters you can think of.

Function to generate very secure passwords

Now I’m going to show you a version of the first function to generate much more secure passwords. In this case, I am going to apply the advice that I gave you in the previous section and I will make some change in the code that ensures a higher level of security.

function password_seguro_random(){
 
    //palabras y caracteres que se utilizarán para crear la contraseña
    $words = 'azote,velociraptor,mantis,friend,srcodigo,fuente,kobold,troll,rings,murloc,testamento';
    $words2 = '.,:,;,*,_,-,!';
    $words3 = 'X,Y,Z,H,H,M,N,Q,O,P';
 
    // partimos las cadenas por las comas:
    $array_words = explode( ',', $words);
    $array_words2 = explode( ',', $words2);
    $array_words3 = explode( ',', $words3);
 
    // Añade una palabra de cada grupo
    $pwd = '';
   $pwd .= $array_words[mt_rand(0, sizeof( $array_words )-1)];
   $pwd .= $array_words2[mt_rand(0, sizeof( $array_words2 )-1)];
   $pwd .= $array_words3[mt_rand(0, sizeof( $array_words3 )-1)];
 
    // añade un número al principio si el password
    $num = mt_rand(1, 99);
    $pwd = $num . $pwd;
   
   //para mayor seguridad modifico un caracter aleatorio de la cadena por un número
   $num = mt_rand(1, 99);
   $pos_random = mt_rand(0, strlen($pwd) - 1 );
   $pwd[$pos_random] = $num;
 
    return $pwd;
 
}

In this function hand increased security through the following changes:

  1. I’ve created three separate variables for the different types of password components. By doing it this way I can make sure later, when I compose the password, that it contains at least one value for each group.
  2. I have added of a random value for each group of symbols/words/characters.
  3. I have added a random number to the beginning of the password.
  4. And finally I have replaced a random position in the string with a number.

Conclusion for getting strong passwords in PHP

Both proposals are valid simple functions to generate passwords in PHP. Although the second option is more recommended if you need trigger passwords robust and difficult to guessthe first option will, for most cases, generate sufficiently strong passwords.

Therefore, I recommend that you use the first version if the password does not protect any kind of banking or sensitive information, and the second option for developments involving data that is susceptible to being stolen or that is dangerous if stolen.

Always remember to encrypt these passwords if you store them in a database or any other support, since their security will be of no use if they access the files that store them.

Leave a Reply