Generate random passwords with PHP

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Generate random passwords with PHP

    In this tutorial I will show you how to generate random passwords that are highly secure and extremely difficult to crack. However you can choose between various complexity/strength and you can set password length as well.


    Step 1.

    Let’s go through what we need to generate passwords. First we need a list of words and/or characters what we can use for password generation. I don’t offer using word lists as it is easier to guess and password recovery tools are using such lists as well. So I will focus only on character lists.

    The idea is to create a string from the characters and than in a loop we select an item from this string (character list) one by one until we reach the requested length. To realize this we will implement a function with 2 parameters. The first is the length of the requested password and the second is the strength/complexity of the password.


    Step 2.

    The function use case looks like this:
    Initializing the PHP random generator using the actual time value.
    Define 3 various strings for the various password complexity.
    Reset the password and length counter variables
    Create a loop until the requested length and append a random character one by one to the password string.
    In the loop I made one more check to make all character different in the generated password.
    Return with the ready password.
    It is quite simple and you can generate really strong passwords with it.

    The complete code looks like this:
    Code:
    <?php
    
    function generatePassword($length=6,$level=2){
    
       list($usec, $sec) = explode(' ', microtime());
       srand((float) $sec + ((float) $usec * 100000));
    
       $validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
       $validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
       $validchars[3] = "0123456789_!@#$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%&*()-=+/";
    
       $password  = "";
       $counter   = 0;
    
       while ($counter < $length) {
         $actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);
    
         // All character must be different
         if (!strstr($password, $actChar)) {
            $password .= $actChar;
            $counter++;
         }
       }
    
       return $password;
    
    }
    ?>
    Step 3.

    To make the script more usable let’s create an html page where the visitor can set the requested length and strength of the password. To do this we will create a simple form with 2 drop down box where the visitor can select the password properties. In this example I set the length list from 5 to 10 and the strength to Easy, Normal, and Hard. When the visitor submits the form it will call itself and in this phase not only shows the form again but processes the submitted values and generates the requested password and shows it for the user.

    The HTML code is quite simple:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
    <html>
    <body>
          <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
            <table>
              <tr><td>Password length: </td><td>
                <select name="passlength">
                  <option value="5">5</option>
                  <option value="6">6</option>
                  <option value="7">7</option>
                  <option value="8">8</option>
                  <option value="9">9</option>
                  <option value="10">10</option>
                </select>
              </td></tr>
              <tr><td>Password strength:</td><td>
                <select name="passstrength">
                  <option value="1">Easy</option>
                  <option value="2">Normal</option>
                  <option value="3">Hard</option>
                </select>
              </td></tr>
              <tr><td ><br/><input type="submit" name="submitBtn" value="Generate"></td></tr>
            </table>
          </form>
    <?php    
        if (isset($_POST['submitBtn'])){
            echo '<table><tr><td>Generated password:</td><td>';
            echo generatePassword($length,$strength);
            echo '</td></tr></table>';
        }
    ?>
    </body>
    Step 4.

    Final words:
    As you can see generating a random password is not so complex task. You can integrate this script into your registration process to generate a password for the user.

    The complete script is the following:
    Code:
    <?php
    
    function generatePassword($length=6,$level=2){
    
       list($usec, $sec) = explode(' ', microtime());
       srand((float) $sec + ((float) $usec * 100000));
    
       $validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
       $validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
       $validchars[3] = "0123456789_!@#$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%&*()-=+/";
    
       $password  = "";
       $counter   = 0;
    
       while ($counter < $length) {
         $actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);
    
         // All character must be different
         if (!strstr($password, $actChar)) {
            $password .= $actChar;
            $counter++;
         }
       }
    
       return $password;
    
    }
    
    ?>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
    <html>
    <body>
          <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
            <table>
              <tr><td>Password length: </td><td>
                <select name="passlength">
                  <option value="5">5</option>
                  <option value="6">6</option>
                  <option value="7">7</option>
                  <option value="8">8</option>
                  <option value="9">9</option>
                  <option value="10">10</option>
                </select>
              </td></tr>
              <tr><td>Password strength:</td><td>
                <select name="passstrength">
                  <option value="1">Easy</option>
                  <option value="2">Normal</option>
                  <option value="3">Hard</option>
                </select>
              </td></tr>
              <tr><td ><br/><input type="submit" name="submitBtn" value="Generate"></td></tr>
            </table>
          </form>
    <?php    
        if (isset($_POST['submitBtn'])){
            echo '<table><tr><td>Generated password:</td><td>';
            echo generatePassword($length,$strength);
            echo '</td></tr></table>';
        }
    ?>
    </body>
Working...
X