A PHP Function To Generate 1 Random Password, Or 2, Or 2… Million…

Now, I am not sure where I originally found this script, or if it is the most efficient way to generate a password in PHP, but it has served me well over the year and I have used it in a few projects.

The good thing about this function in particular, is that it allows you to define the letters and symbols used in all of your random passwords. This might be important to you if you want to remove some of those that are commonly confused, such as 0 and O, or S and 5, or I and l, etc, etc.

The Function

function createRandomPassword($length=12) {
  $vowels = 'bdghjmnpqrstvz23456789!^()';
  $consonants = 'bdghjmnpqrstvzBDGHJMNPTVX';
  $password = '';
  $alt = time() % 2;
  for ($i = 0; $i < $length; $i++) {
    if ($alt == 1) {
      $password .= $consonants[(rand() % strlen($consonants))];
      $alt = 0;
    } else {
      $password .= $vowels[(rand() % strlen($vowels))];
      $alt = 1;
  return $password;


Generating 1 password

If you need only one password, it is nice and easy to call this function and simply echo out the password like below. You can set the length by placing a single number in between the brackets.

echo createRandomPassword(8);

Generating 2 To 2 Million Passwords

Well, maybe you wouldn’t want to generate to 2 million passwords, but say you want a whole batch. You can easily use a php for loop to create as many as you like. Simply change the second parameter in the for loop (which is 10 in the below example) to how many passwords you need.

for ($x = 0; $x <= 10; $x++) {
   echo createRandomPassword(8) . '<br>';

I hope this helps someone 🙂

Oh, and the cool featured image was by Jason Leung on Unsplash