Generate a random password – PHP function

Generate a random password - PHP functionSometimes, coming up with a half decent password can be a little daunting. Although it’s easier to remember one made up of your surname, or the name of your favourite pet, for improved security, it’s better to choose something a little more random. The following random password PHP function generates a password on a variable character length.

Create random password function

Let’s start by making a container for our random password function:

/// RANDOM PASSWORD
function generate_random_password()
{
}
///

Now, let’s add some srand() to generate the random password:

/// RANDOM PASSWORD
function generate_random_password()
{
 $char = "abcdefghijkmnopqrstuvwxyz023456789"; /// ALLOWED CHARS
 srand((double)microtime()*1000000); /// 'RANDOMISER'
}
///

Now that we have established the parameters of our function, let’s add a loop to generate a random sequence to the value of ‘$length’:

/// RANDOM PASSWORD
function generate_random_password($length)
{
 $char = "abcdefghijkmnopqrstuvwxyz023456789"; /// ALLOWED CHARS
 srand((double)microtime()*1000000); /// 'RANDOMISER'
 /// START LOOP
 $x = 1;
 while ($x <= $length) {
  $gen = rand()%33;
  $single = substr($char, $gen, 1); /// -1 CHARACTER FROM $CHAR
  $pass .= $single; /// ACCUMULATE SINGLE RANDOM CHARACTER
 $x++;
 }
 /// END LOOP
 return $pass;
}
///

Usage:

<?php
echo generate_random_password(10); /// 10 CHARS LONG
?>

This will output a randomised sequence of characters, 10 characters in length.

Leave a Reply

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