How to create random alphanumeric password in PHP

At times, you may need to generate and provide your website user with a new or default password. For example, if a user has forgotten his/her password then you may need to generate a new password for him/her.

Or you may want to provide default password to newly registered users after they have verified their e-mail address. It is obvious that password generated in these circumstances should be random in nature.

Here, I will show you an easy way to generate random alphanumeric password in PHP.

We will create a function named generate_random_password() for generating password. It will take an optional parameter, $length, which will define the length of the password. Create a new PHP file and add the following code to it:

<?php function generate_random_password($length = 10) { $alphabets = range('A','Z'); $numbers = range('0','9'); $additional_characters = array('_','.'); $final_array = array_merge($alphabets,$numbers,$additional_characters); $password = ''; while($length--) { $key = array_rand($final_array); $password .= $final_array[$key]; } return $password; } echo 'Random password generated is "<b>' . generate_random_password(15) . '</b>".'; ?>

In the above code we have used the range() function to automatically generate sequence of alphabets and numbers which are stored in variables $alphabets and $numbers respectively. We have also defined an additional array named $additional_characters which contains any additional character that we may want to use in our password.

After this we merge all the three arrays together with the help of array_merge() function and store the result in the resultant array $final_array. Also, we have declared $password variable which will contain our final generated password.

Next, we use array_rand() function to pick a random key from the resultant array. We append the character corresponding to this random selected key from the resultant array to $password variable. We keep doing this in a while loop until we have created the password of desired length. Finally, we return the randomly generated password. The output is shown below:

Randomly generated alphanumeric password in PHP