How To Generate Random Password In PHP?

Today in this post we are going to see how to generate a random password with PHP. You can see on lots of websites and web-based applications generating random passwords when a user registered.

Now let’s see how to generate password randomly with PHP programming language.

We are going to make a PHP function which will generate a random password. Below is the given code of that PHP function:

function generate_pw() {
  // Set random length for password
  $password_length = rand(8, 16);
  $pw = '';

  for($i = 0; $i < $password_length; $i++) {
    $pw .= chr(rand(32, 126));
  return $pw;

The above function will return the randomly generated password. You just need to call the function like any other PHP function and it will return the password.

Get country data by clicking on map – PHP source code

AJAX search from MySQL database in PHP example

Here we have first declared the length of the password in the variable $password_length. The length of the password can be anything between 8 to 16 as we have set the random value between 8 and 16 with the PHP rand function which is rand(8, 16).

After that, we have declared a variable $pw and assign the blank string to it. Then we start a for loop which generates a random character between ASCII code 32 to 126. This process will repeat as $length times. Thus it will generate the password between the ASCII value 32 and 126.

How to convert JSON string to PHP Array?

Set cookie and retrieve it on web page in PHP

How to use the random password generating function?

It is very simple to use the function that we have just build. The code below will display a randomly generated password on the web page.

   echo generate_pw();

You can further modify the function and you can change the ASCII range as per as your requirement.

Leave a Reply

Your email address will not be published. Required fields are marked *