Generate Random Strong Password With PHP

In this tutorial, we will learn how to generate random strong password in PHP.

Generally we see to secure a website or blog we need to keep strong password for authentication system.

In this post, we will see how to generate random strong password to secure login access of site or blog. When we login to control panel of hosting we get an option to generate strong password for FTP connection, Webmail login and Cpanel login access.

We will see how to get strong password using PHP.

Let us discuss about tutorial.

Have a look on given below snippet.

<?php
function password($length){
$alphabetical = range('A','Z');
$numeric =  range('0','9');
$special = array('/','\\',':',';','!','@','#','

In the above snippet we use alphabetical character, numeric and special character to generate strong password. Then array_merge() function is used to merge all the three array shown above.

Now merged array is passed in array_rand() function to get all keys in loop. Finally we get password value stored in $merged_password stored on each key. Each password value is stored in $final_password variable one by one. To generate random strong password just call function password($length) and pass the length of password in function. That’s it.

<?php
function password($length){
$alphabetical = range('A','Z');
$numeric = range('0','9');
$special = array('/','\\',':',';','!','@','#','$','%','^','*','(',')','_','+','=','|','{','}','[',']','"',"'",'<','>',',','?','~','`','&',' ','.');
$merged_password = array_merge($alphabetical,$numeric,$special);
$final_password = " ";
for($i=$length;$i>0;$i--)
{
$keys = array_rand($merged_password);
$final_password  .= $merged_password [$keys];
}
 return $final_password;
}
//call function 
echo password(12);
?>

In the above snippet we use alphabetical character, numeric and special character to generate strong password. Then array_merge() function is used to merge all the three array shown above.

Now merged array is passed in array_rand() function to get all keys in loop. Finally we get password value stored in $merged_password stored on each key. Each password value is stored in $final_password variable one by one.

To generate random strong password just call function password($length) and pass the length of password in function.

That’s it.

Leave a Comment