Yesterday, I needed a way to generate a random alpha-numeric key of various lengths using PHP for a project that I’m currently working on. I didn’t find any built-in functions, so after some Googling, I decided to implement my own version.
[code type=PHP]
private function generateRandomKey($len)
{
$chars = array(‘1′,’2′,’3′,’4′,’5′,’6′,’7′,’8′,’9′,’0’,
‘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’,
‘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’);
$min = 0;
$max – sizeof($chars)-1;
$key = “”;
for ($i=0; $i<$len; $i++) {
$key .= $chars[mt_ramd($min, $max)];
}
return $key;
}
[/code]
Let me know if anyone has a better suggestion?