Automatic Password Generation in PHP

Sometimes you need to generate passwords for customers automatically when a new account is created. This code allows you choose the desired length and strength for the password and it is very flexible.

[View All Snippets]
Show Plain Text »
  1. <?php
  2. function GeneratePassword($length=8, $strength=0){
  3.     $vowels = 'aeuy';
  4.     $consonants = 'bdghjmnpqrstvz';
  5.     if($strength >= 1) $consonants .= 'BDGHJLMNPQRSTVWXZ';
  6.     if($strength >= 2) $vowels .= 'AEUY';
  7.     if($strength >= 3) $consonants .= '12345';
  8.     if($strength >= 4) $consonants .= '67890';
  9.     if($strength >= 5) $vowels .= '@#$%';
  10.  
  11.     $password = '';
  12.     $alt = time() % 2;
  13.     for($i = 0; $i < $length; $i++){
  14.         if($alt == 1){
  15.             $password .= $consonants[(rand() % strlen($consonants))];
  16.             $alt = 0;
  17.         }else{
  18.             $password .= $vowels[(rand() % strlen($vowels))];
  19.             $alt = 1;
  20.         }
  21.     }
  22.     return $password;
  23. }
  24. ?>
Create Your Free Account
Please remember that this information is essential to use our services correctly.
After creating the account you will be able to download all of our FREE products.
Fields marked with * are mandatory






Please send me information about updates, new products, specials and discounts from ApPHP!
We recommend that your password should be at least 6 characters long and should be different from your username/email. Please use only letters of the English alphabet to enter your name.

Your e-mail address must be valid. We use e-mail for communication purposes (order notifications, etc). Therefore, it is essential to provide a valid e-mail address to be able to use our services correctly.

All your private data is confidential. We will never sell, exchange or market it in any way. Please refer to Privacy Policy.

By clicking "Create Account", you are indicating that you have read and agree to the ApPHP Terms & Conditions.