Page 1 of 1
Generating random key
Posted: Sat Dec 19, 2009 3:48 pm
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.
Re: Generating random key
Posted: Sat Dec 19, 2009 4:44 pm
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.
Re: Generating random key
Posted: Mon Dec 21, 2009 10:18 am
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.
Re: Generating random key
Posted: Mon Dec 21, 2009 10:31 am
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

Re: Generating random key
Posted: Mon Dec 21, 2009 10:39 am
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.