Generating random key

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
fellow21
Forum Newbie
Posts: 1
Joined: Sat Dec 19, 2009 3:40 pm

Generating random key

Post by fellow21 »

Hello. I’m just asking for advice as opposed to posting code samples, so I apologise in advance if this is an inappropriate place.

I’m looking to generate a random key, possibly a combination of numbers, which will be sent to a user via email once they have created an account. The problem I have is that I don’t know where to start! Which PHP function could generate a random key and how would I include this in an email?

Thank you very much in advance for any guidance or pointers you can offer me.
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Generating random key

Post by Apollo »

See the uniqid or mt_rand functions.

Just either uniqid() or mt_rand() would do, but in particular, this:

Code: Select all

$randomKey = md5(uniqid(mt_rand(),true));
will give a perfectly random hexadecimal key.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Generating random key

Post by pickle »

I assume this will be a sort of activation code? If so, you'll want to make sure (as in, guarantee) it's unique - you'll need to use a database for that.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Generating random key

Post by Apollo »

pickle wrote:I assume this will be a sort of activation code? If so, you'll want to make sure (as in, guarantee) it's unique - you'll need to use a database for that.
I doubt if the probably of md5(uniqid(mt_rand(),true)) giving the same ID twice, is significantly larger than the probability of a quantum fluctuation in one of the silicon atoms in your SQL server's memory, causing a duplicate ID not to be detected.

There's no such thing as '100% guarantee' in our world ;)
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Generating random key

Post by pickle »

Actually, there are only 16^32 (which, admittedly is a lot) possible MD5 hashes. There's nothing saying two random strings won't be hashed to the same thing. Whether you're passing MD5 a random string, or an iterated string doesn't really matter either - the point of hashing is that the hashes are not supposed to be predictably relevant to the string their generated from.

There is a 100% guarantee - knowing what you've already generated and checking against that.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply