Create Random Password with PHP

If you create a webpage, where users can register themself, it is good to send them for the first login a radom created password. This helps you to check, if the entered email address is valid. without a valid email address they are not able to login into your service.

But how can you do this? It is really easy to create a good and secure password with a small function in PHP.

function createRandomPassword() {
  $chars = "$?§%ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789"; // an array with all characters which can be used for the password
  srand((double)microtime()*1000000); // creates the start value for the random number, not necessarysince PHP 4.2.0 anymore but can be used
  $i = 0;
  $pass = '' ;
  while ($i <= 20) { // number of signs for the password
    $num = rand() % 64; // chooses randomized a number (64 is the count of signs in the array)
    $tmp = substr($chars, $num, 1); // selects the radomized selected sign out of the array
    $pass = $pass . $tmp; // adds the sign to the password
  return $pass; // gives back the created password string

Print Friendly, PDF & Email

One thought on “Create Random Password with PHP

Leave a Comment

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.