Random Password Generation
Simple class to generate random passwords with working example
<?php
// just so we know it is brokenerror_reporting(E_ALL);
/*
*
* string passType can be alpha, numeric, or alphanumeric defaults to alphanumeric
* int $length is the length of the password, defaults to eight
*
*/class randomPassword{
function __construct($passType='alphanumeric', $length=8, $rangeLength=9){
$this->setLength($length);
$this->setRangeLength($rangeLength);
$this->passType = $this->setPassType($passType);
}
function setRangeLength($rangeLength){
$this->rangeLength=$rangeLength;
}
// set the length of the passwordprivate function setLength($length){
$this->length=$length;
}
// set the type of passwordprivate function setPassType($passType){
return $passType.'Chars';
}
// return an array of numbersprivate function numericChars(){
return range(0, $this->rangeLength);
}
// return an array of charsprivate function alphaChars(){
return range('a', 'z');
}
// return an array of alphanumeric charsprivate function alphaNumericChars(){
return array_merge($this->numericChars(), $this->alphaChars());
}
// return a string of charsprivate function makeString(){
// here we set the function to call based on the password type
$funcName = $this->passType;
return implode($this->$funcName());
}
// shuffle the chars and return $length of charspublic function makePassword(){
return substr(str_shuffle($this->makeString()), 1, $this->length);
}
} // end class
function randomPassword($length) {
// create an array of chars to use as password
$chars = implode(array_merge(range(0,9), range('a', 'z')));
// randomly snarf $length number of array keys
return substr(str_shuffle($chars), 1, $length);
}
echo randomPassword(8).'<br />';
try
{
$obj = new randomPassword('alphanumeric', 16, 100);
echo $obj->makePassword().'<br />';
}
catch(Exception $ex)
{
echo $ex->getMessage();
}
?>
0 comments:
Post a Comment