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!

Add This!