Board logo

subject: PHP Random Password Generator Script [print this page]


PHP Random Password Generator Script
PHP Random Password Generator Script

Password is a gateway for our services, and we can't compromise on the security of password. Today i am going to write a tutorial that will help the PHP developers of every level to create a secure, powerful and easy to use random password generator algorithm.

Step 1: Four Important Inputs to Create Random Password

We will choose four simple inputs to construct our password. These inputs will generate a password that will hard to guess.

Length of Password (User Input)

Lower Case Letters (a-z)

Upper Case Letters (A-Z)

Numbers (0-9)

Symbols (~!@ etc)

Step 2: Arrange Inputs in PHP Array

I love array(s), as they give a flexible power to handle complicated logic's easily. So i will recommend to arrange these inputs in the form of Array like,

$alpha_upper = array( "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");

$alpha_lower = array( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");

$number = array( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 );

$symbol = array( "-", "_", "^", "~", "@", "&", "|", "=", "+", ";", "!", ",", "(", ")", "{", "}", "[", "]", ".", "?", "%", "*", "#" );

Step 3: Merge Inputs in a Global Array

So we have collected basic inputs to construct our password. I am going to merge all these inputs in a global array, that will help us to mix them easily.

$global = array();

$global = array_merge( $global, $alpha_upper);

$global = array_merge( $global, $alpha_lower);

$global = array_merge( $global, $number);

$global = array_merge( $global, $symbol);

Step 4: Shuffle to Generate a Random String for Password

I will use a simple, built-in method of PHP for the sake of accuracy and speed to shuffle our global array.

shuffle($global);

Step 5: Generate Random Password with PHP

Now it is a final step to accomplish our task. We have prepared our ingredients (inputs) to generate a good, powerful, secure and hard to guess password. Let's play with a simple logic by using the power of foreach loop.

$password = '';

foreach( $global as $val ) {

$password .= $val;

if( strlen($password) == $length ) {

break;

}

}

Step 6: Print Password

Password is ready to print, and i hope you will like this logic.

Try Online Demo

Download PHP Password Generator Class




welcome to loan (http://www.yloan.com/) Powered by Discuz! 5.5.0