Generate random password with PHP rand function

Posted by Shek on May 8, 2011 under PHP | Be the First to Comment | Total View: 4,929 views

In system designing, there are many cases which requires user to login in order to access some restricted areas. And so, we might need to generate an initial password for the user. Here I am going to show you how to generate random passwords with integers


In order to generate a random password we have to decid the length (how many digits) for the password.

Lets say 9:
For each of the ditigal we use PHP function rand() to generate an integer between 0-9:

1
$randpassword = rand(0, 9);

Because we need 9 digits and so we repeat 9 times:

1
$randpassword = rand(0, 9).rand(0, 9).rand(0, 9).rand(0, 9).rand(0, 9) .rand(0, 9) .rand(0, 9) .rand(0, 9) .rand(0, 9);

and to make it easy to manage, we use a for loop to do it:

1
2
3
4
for($i = 0; $i<9; $i++){
$randpassword .= rand(0, 9);
}
echo $randpassword;

To make it more easy to altar the length of the password in the future, we add a variable $passlength to store the length:

1
2
3
4
5
$passlength = 9;
for($i = 0; $i<$passlength; $i++){
$randpassword .= rand(0, 9);
}
echo $randpassword;

Therefore we could change the length by changing the $passlength.

Not what you want? Try a Search

Add A Comment

*