PHP: random password generator

This service allows generating random passwords with a specific structure, where in each position of the password the presence of consonants or vowels in upper or lower case, or the presence of numbers may be customized. By defining the structure of the password it is possible to generate a easier to read password.

To generate a random password a code must be provided.

Some code examples:
    "XXXXXXXX" (hard to read)
    "CVcvcvNN" (readable)
    "VCVCNNNN" (readable with 4 digits)
    "VNNNNc" (mostly digits)

(by clicking in the links above 10 random passwords with the specified structure will be generated)

where
    X means any letter (both upper case and lower case) or number
    C means an upper case consonant
    c means a lower case consonant
    V means an upper case vowel
    v means an lower case vowel
    N means a number 0 to 9


 
random_password.php
<?php

print generatepassword("CVcvcvNN");

function generatepassword($code){
    // 21 consonants (0 to 20)
    $consonants  = "BCDFGHJKLMNPQRSTVWXYZ";
    //  5 vowels     (0 to  4)
    $vowels = "AEIOU";
    // 62 options (0 to 61)
    $all  = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    // our variable
    $password="";

    // split the code into separated characters
    $array=preg_split("//",$code,-1,PREG_SPLIT_NO_EMPTY);
    
    // for each character in code assign ....
    foreach ($array as $k => $type){
        // ... any letter or digits
        if($type=="X" or $type=="x"){
                $password.= substr($all,mt_rand(0,61),1);
        }
        // ... a consonant, upper case
        if($type=="C"){
                $password.= substr($consonants,mt_rand(0,20),1);
        }
        // ... a consonant, lower case
        if($type=="c"){
                $password.= strtolower(substr($consonants,mt_rand(0,20),1));
        }
        // ... a vowel, upper case
        if($type=="V"){
                $password.= substr($vowels,mt_rand(0,4),1);
        }
        // ... a vowel, lower case
        if($type=="v"){
                $password.= strtolower(substr($vowels,mt_rand(0,4),1));
        }
        // ... a number
        if($type=="N" or $type=="n"){
                $password.= mt_rand(0,9);
        }

    }
    return $password;
}

?>

 

PHPTutorial.info.