In some applications, it can be useful to generate a random password, such as setting the user's initial password and then letting the user change it if he or she wishes. The function shown in the following code generates a password with a number of random characters, and you can set the length of the password when you call the function:
<?php
function randomPassword($length) {
$possibleCharacters = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$characterLength = strlen($possibleCharacters);
$seed = (double) microtime() * 1000000;
srand($seed);
$password = "";
for($i=1;$i<=$length;$i++){
$character = rand(1,$characterLength);
$character = substr($possibleCharacters,$character, 1);
$password .= $character;
}
return $password;
}
?>
To call the function, you can use the following code:
<?php $randomPassword = randomPassword(8); echo $randomPassword; ?>
This would create a random eight-character password—for example, VcF1TG65 or BJuNj7ao.
To create the password, first you set up a string containing characters that can be used for the password. You then find the number of characters in the string with the PHP strlen function.
Next, you seed the PHP random number generator and use it to create a random number between 1 and the number of characters that can be used. The seed is first created by using the PHP microtime function to return the number of seconds since the Linux epoch date, and you then multiply this by 1 million so that you have a whole number, which will be different each time the code is run. Next, you use this number as a seed for the random number generator using the PHP srand command, so that it generates truly random numbers. Note that with PHP version 4.2.0 and upward, you don't have to seed the random number generator as it's done automatically.
This random number is then used to extract a single character from the string of allowed characters by reading the character at the position in the string equal to the random number. This character is then added to the new password, until the number of characters in the password matches the number specified when the function was called.
Our website is not responsible for the information contained by this article. Webworldarticles.com is a free articles resource thus practically any visitor can submit an article. However if you notice any copyrighted material, please contact us and we will remove the article(s) in discussion right away.
This article was sent to us by:
Stratus Huo Quan at
12102007
1. Benefits of PHP programmers in freelance programming industry
All articles in this directory are property of their respective authors. Additionally, read our Privacy Policy
© 2010 WebWorldarticles.com - All Rights Reserved. Partners: Gunblade Saga