Random Key Generator in PHP
July 31st, 2007 by Tom Glenn
Whilst developing the new UKCashFlow, I came across the need to generate a random “key” or “token” for each member when they signed up. I’ve never really knew how to go about doing this before, and always ended up copy and pasting code. But I finally knuckled down and learnt how to do it. So, for any of you who may need to solve a similar problem, here you are:
(To generate a password rather than a key, you probably want to set $sections to 1)
// Function to create a new random token
// e.g. createToken('UG8D-', 3, 4)
// Might produce: UG8D-6T8Y-FCK7-09PL
function createToken($tokenprefix, $sections, $sectionlength)
{
// Declare salt and prefix
$token.=$tokenprefix;
$salt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
// Prepare randomizer
srand((double)microtime() * 1000000);
// Create the token
for($i=0; $i< $sections; $i++)
{
for($n=0; $n<$sectionlength; $n++)
{
$token.=substr($salt, rand() % strlen($salt), 1);
}
if($i<($sections-1)){ $token.='-'; }
}
// Return the token
return $token;
}
echo(createToken('', 1, 6));
I hope this can be of some use to some of you!
Posted in Web Development · 1 Comment
Trackback URL:
http://tomglenn.co.uk/webdev/random-key-generator-in-php/trackback/







January 15th, 2008 at 4:25 am
If you’re creating password that someone may need to type out, it’s sometimes good to leave out the number 0(zero) and the capital letter O(’oh’) as they can sometimes look almost identical. May save some confusion(although most people will figure it out).