Tuesday, August 18, 2009

Generate random alphanumeric password in Php

A simple function which returns an autogenerated random alphanumerical password with the specified length.


Code:

<?
function NewPassword($len = 8)
{
$chars=array(
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P",
"Q","R","S","T","U","V","W","X","Y","Z", //upper-case
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p",
"q","r","s","t","u","v","w","x","y","z", //lower-case
"0","1","2","3","4","5","6","7","8","9" //numbers
);

srand((float) microtime() * 10000000);
$array=array_rand($chars, $len);

$password="";
foreach ($array as $key => $val)
$password.=$chars[$val];

return $password;
}
?>

No comments: