Generate Random Password with PHP

generate random password with php

(You can download the complete “Generate Random Password with PHP” file from the right sidebar. Click on “Download Attachment” button)

In this simple and short tutorial we are going to learn how to generate random password with php.

When creating web apps, there is often a need to generate a random password for your new or existing users. There are a number of ways to do this, but in needing to do it recently I came up with this very simple function that will generate a random password (or any other random string) of whatever length you wish. It’s particularly useful when generating passwords for users that they will then change in the future. It uses PHP’s handy str_shuffle() function:

function generate_password($chars = 8) {
   $letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?";
   return substr(str_shuffle($letters), 0, $chars);
}

To generate random password simply pass the desired length of password in this function. If you omit length parameter then it will generate 8 character long password by default.

// default length 8
$rand_password1 = generate_password();

// 12 character long password
$rand_password2 = generate_password(12);

Now, when you want to use these variables you can simply use them or echo them out.

echo $rand_password1;

// Adding a line break between them.
echo "<br>";

echo $rand_password2;

(You can download the complete “Generate Random Password with PHP” file from the right sidebar. Click on “Download Attachment” button)

Functions Used: