Page 1 of 1

Random Alphanumeric Generator

Posted: Thu Apr 15, 2010 3:47 am
by bcart
Hi there

I am currently writing an exam booking system which seems to be working except for one vital part. This is what happens...

A user registers the learners details. At this point I use a Random Alphanumeric Generator to return a unique booking reference which is used at the checkout to bring back all the details of their booking.

However, sometimes it doesn't seem to work. When I look at the database I see that (in one example) it has generated the same alphanumeric value which is why at the checkout it returns more than what the person thought they had booked.

Here's the code for the generator...

Code: Select all

function randomPrefix($length)
		{
		$random= "";
		
		srand((double)microtime()*1000000);
		
		$data = "AbcDE123IJKLMN67QRSTUVWXYZ";
		$data .= "aBCdefghijklmn123opq45rs67tuv89wxyz";
		$data .= "0FGH45OP89";
		
		for($i = 0; $i < $length; $i++)
		{
		$random .= substr($data, (rand()%(strlen($data))), 1);
		}
		
		return $random;
	}
After this has run I assign it to a session variable.

Can anyone help?

Cheers!

Re: Random Alphanumeric Generator

Posted: Thu Apr 15, 2010 3:57 am
by timWebUK
Encode and add something to the random generator that is unique to the booking. Such as their username, etc

That way you shouldn't get collisions.

Re: Random Alphanumeric Generator

Posted: Thu Apr 15, 2010 8:38 am
by solid
php.net:
string uniqid ([ string $prefix = "" [, bool $more_entropy = false ]] )
Gets a prefixed unique identifier based on the current time in microseconds.
You will want to take advantage of the $prefix param

Re: Random Alphanumeric Generator

Posted: Thu Apr 15, 2010 10:51 am
by AbraCadaver
No matter how you generate the random sequence, after it is generated query the database to see if it exists already. If so, then generate another one and check, etc...