In the web application needs to generate a random password in PHP for new users. There are many ways to generate a random string in PHP. Using this way you can generate any length of a strong password.
here I specify two methods for generate a random password
1) Using str_shuffle() Function.
2) Using rand()
I tried both methods to generate a random password. if you know any other methods to generate random character then please mention it in the comment box.
here I specify two methods for generate a random password
1) Using str_shuffle() Function.
2) Using rand()
1) Generate Random Password Using str_shuffle() Function.
strt_shuffle() method randomly shuffles your string. Here also use substr() method which method return the part of the string.<?php
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$a = substr(str_shuffle($chars),0,8);
?>
2) Generate Random Password Using rand() Function
rand() function generate a random string or integer number. Here first we count the total character from we can generate the random string. After counting total character, we generate the random number between the total counted character and take the character of that number.<?php
$char = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$password = array();
$charlength = strlen($char) - 1; // here $charlength=59
for ($i = 0; $i < 8; $i++)
{
$n = rand(0, $charlength); // here $n = any random number between 0 to 59
$password[] = $char[$n]; // $password[] = $nth position character
}
?>
I tried both methods to generate a random password. if you know any other methods to generate random character then please mention it in the comment box.
COMMENTS