PHP Generate random password
From JumbaWiki
This is a simple PHP function that generates a random password. To call the function simply run createPassword(8); - to define how many characters you want in the password, enter the number in the function call, eg. createPassword(10);. (from http://www.totallyphp.co.uk)
Note: The letter l (lowercase L) and the number 1 have been removed from the possible options as they are commonly mistaken for each other.
<?php function createPassword($length) { $chars = "234567890abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; $i = 0; $password = ""; while ($i <= $length) { $password .= $chars{mt_rand(0,strlen($chars))}; $i++; } return $password; } $password = createPassword(8); echo "Your 8 character password is: $password"; ?>
- Code contributed by Thewebdruid, for the Jumba Wiki
Here's another variation that accepts a second (optional) parameter, allowing you to specify what kind of characters the password can contain:
<? function RandomPassword($PwdLength=8, $PwdType='standard') { // $PwdType can be one of these: // test .. .. .. always returns the same password = "test" // any .. .. .. returns a random password, which can contain strange characters // alphanum . .. returns a random password containing alphanumerics only // standard . .. same as alphanum, but not including l10O (lower L, one, zero, upper O) // $Ranges=''; if('test'==$PwdType) return 'test'; elseif('standard'==$PwdType) $Ranges='65-78,80-90,97-107,109-122,50-57'; elseif('alphanum'==$PwdType) $Ranges='65-90,97-122,48-57'; elseif('any'==$PwdType) $Ranges='40-59,61-91,93-126'; if($Ranges<>'') { $Range=explode(',',$Ranges); $NumRanges=count($Range); mt_srand(time()); //not required after PHP v4.2.0 $p=''; for ($i = 1; $i <= $PwdLength; $i++) { $r=mt_rand(0,$NumRanges-1); list($min,$max)=explode('-',$Range[$r]); $p.=chr(mt_rand($min,$max)); } return $p; } } // TEST SCRIPT $numchar=9; foreach(array('standard','alphanum','any','test') as $type) { echo "<br /><br />Sample $numchar character \"$type\" password:<br /> "; echo RandomPassword($numchar,$type); } ?>

