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:
Now lets explains the important components:
randpassword() is the function name to call it later for use.
$length variable holds the number of characters to generate while passing it to the for loop condition.
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 loop to get the condition and loop it until the loop finished.
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()].
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.
Shindan Theme By Arif for anl4u.com blog / Copyright © 2009-2013