Random Alphanumeric Generator

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bcart
Forum Newbie
Posts: 10
Joined: Fri Oct 30, 2009 8:09 am

Random Alphanumeric Generator

Post 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!
User avatar
timWebUK
Forum Contributor
Posts: 239
Joined: Thu Oct 29, 2009 6:48 am
Location: UK

Re: Random Alphanumeric Generator

Post 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.
solid
Forum Commoner
Posts: 28
Joined: Wed Aug 12, 2009 11:56 am

Re: Random Alphanumeric Generator

Post 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
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Random Alphanumeric Generator

Post 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...
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply