This design is still under development!

Simple Password Generator

Step 1:

First we will start of by creating a function, this will make it easy to use in the future as described in the how to use segment.


    function password($length){

    }
        

Step 2:

Now we need some characters which we will later use in creating the password, you can customize these if you want to. In this example we will be using uppercase letters, lowercase letters, numbers and special charaters. Bare in mind that some special charaters can cause some complications in your code if you echo them out and you should therefore research this before adding those.


    $uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz';
    $digits = '0123456789';
    $specialCharacters = '!#$%&*?@';
        

Step 3:

Now we will merge all the character sets together into one string, this provides easy handling in the next step.


    // Merges the characters into one string.
    $passwordCharacters = $uppercaseLetters . $lowercaseLetters . $digits . $specialCharacters;
        

Step 4:

This is the last step in the process, here we take the string we just made with all the character sets and shuffle it so the order is random. Then we cut it down to the desired length and returns it so it can be either displayed or handled.


    // Shuffles the string and cuts down the string to the selected lenght of the password.
    return substr(str_shuffle($passwordCharacters), 0, $length);
        

Final result:


    function password($length){
        
        $uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz';
        $digits = '0123456789';
        $specialCharacters = '!#$%&*?@';
        
        // Merges the characters into one string.
        $passwordCharacters = $uppercaseLetters . $lowercaseLetters . $digits . $specialCharacters;
        
        // Shuffles the string and cuts down the string to the selected lenght of the password.
        return substr(str_shuffle($passwordCharacters), 0, $length);
    }
            

How to use:

Now to use the password generator you have to write the code below, where the parameter in the parentheses is the number of characters you want in the password.


    echo password(10);
        

Making error messages:

If you want error messages displayed, simply put this code in the start of the function.


    // Simple error messages.
    
    if(!is_int($length)){
        return "Length of password have to be a integer";
    }
    if(!isset($length) || $length < 10){
        $length = 10; // Makes 10 the default length of the password if no number is inserted or length is under 10.
    }