Generate Random Password in PHP


While working on a project last week, i implemented a function to generate random password by calling it. There are many styles of password generator available over the net, but it depends which one suits our taste and need. The function i used has the ability of creating random password from the given set of characters with digits. So lets have a look at the code 1st and explain it after that:

< ?php
function  randpassword() {
$length = 8;
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
$string = "";

for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters)-1)]; } return $string; } echo randpassword(); ?>

Now lets explains the important components:

function randpassword() {

randpassword() is the function name to call it later for use.

$length = 8;

$length variable holds the number of characters to generate while passing it to the for loop condition.

$characters = "0123456789abcdefghijklmnopqrstuvwxyz";

Important part of the function to tell the function to use these characters and numbers for the password, you can change it according to the need like using capital alphabets or both.

for ($p = 0; $p < $length; $p++) {

For loop to get the condition and loop it until the loop finished.

$string .= $characters[mt_rand(0, strlen($characters)-1)];

Another important part of the function in the for loop condition to analyze the characters. $characters are coming from the variable above. mt_rand() is PHP function to return the desired min and max number given to it. For example mt_rand(2,10) will generate random numbers between 2 and 10. In the above line, we pass 0(zero)  and then characters length with -1, please note that -1 is necessary here to avoid index out of bounds error. If you miss -1, the function will sometime generate 7 characters with error index out of bound but mentioned above 8 to generate. That’s because we are using mt_rand function which will sometime return integer $max and there will be no proper value in $characters[strlen()].

return $string;
echo randpassword();

And the last return $string will return the string value stored in it and then just echo it to see the outcome of the function.  You can save it in database or send it to user before storing a hash of it in database.

That’s it easy and simple.

Search

Articles

What's Hot

Recent Comments