Generating random strings - passwords, ref codes etc
algis
Often I need to generate a random string for a password, a ref code or something. So I have made this little PHP class. It is configured to use caps and digits.
For example, if you need to make up a reference number, something like H7-UE4-3GG, here is the sample code:
$gen = new aaRandomPasswordGenerator; $gen->useLetters = false; $gen->useCaps = true; $gen->useDigits = true; $components = array(); $components[] = $gen->generate( 2 ); $components[] = $gen->generate( 3 ); $components[] = $gen->generate( 3 ); $refno = join( '-', $components );
Class code:
class aaRandomPasswordGenerator {
var $useLetters;
var $useCaps;
var $useDigits;
function aaRandomPasswordGenerator(){
$this->lettersSalt = 'abcdefghijklmnopqrstuvxyz';
$this->capsSalt = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
$this->digitsSalt = '0123456789';
$this->useLetters = true;
$this->useCaps = true;
$this->useDigits = true;
}
function generate( $len ){
$salt = '';
if( $this->useLetters )
$salt .= $this->lettersSalt;
if( $this->useDigits )
$salt .= $this->digitsSalt;
if( $this->useCaps )
$salt .= $this->capsSalt;
srand( (double) microtime() * 1000000 );
$pass = '';
$i = 1;
while ( $i <= $len ){
$num = rand() % strlen($salt);
$tmp = substr($salt, $num, 1);
$pass .= $tmp;
$i++;
}
return $pass;
}
}
Posted in PHP Application Development |
No Comments »