tags:

views:

388

answers:

2

Using PHP, what are some ways to generate a random confirmation code that can be stored in a DB and be used for email confirmation? I can't for the life of me think of a way to generate a unique number that can be generated from a user's profile. That way I can use a function to make the number small enough to be included in the URL (see this link). Remember, the user has to click on the link to "confirm/activate" his/her account. If I can't use numbers, I have no problems using both letters and numbers.

With that said, I've tried hashing the username along with a "salt" to generate the random code. I know there has to be a better way, so let's hear it.

+5  A: 
$random_hash = md5(uniqid(rand(), true));

That will be 32 alphanumeric characters long and unique. If you want it to be shorter just use substr():

$random_hash = substr(md5(uniqid(rand(), true)), 0, 16); // 16 characters long
John Conde
+1 Nice and unique and not based on user data. That said, I *think* the rightmost portion of uniqid is more unique that the left, so you'd probably want to use -16, 16 for the substr.
middaparka
And before the inevitable question comes up: You would have to hash about 18,000,000,000,000,000,000 items before you had a 50% likelyhood of getting two of the same hash. That's one hash every millisecond for 584 million years. So yes, they will be unique.
BlueRaja - Danny Pflughoeft
Yea, thanks guys! This along w/ querying against the hash code and username should be good enough, no?
luckytaxi
@middaparka, excellent tip!
John Conde
+2  A: 

1) Create an Activated Field in Database

2) After registration the Email is sent

3) Create a Link to include in Email,Use a Unique identifier It would look something like this

Welcome Username Thanks for registering.

Please Click on the Link below to activate your account

domain.com/register.php?uid=100&activate=1

4) Update the Activated Field to true

alt text

$email_encrypt = urlencode($email);
$special_string = 'maybeyourcompanynamereversed?';
$hash = md5($email_encrypt.$special_string);

Here is the link that is sent to the email that was provided:

http://yourdoman.com/confirm.php?hash='.$hash.'

The actual link will look something like this:

http://yourdomain.com/confirm.php?hash=00413297cc003c03d0f1ffe1cc8445f8
streetparade
+1 for the pic as well as the code. Using the DB is helpful to to keep track of the codes... and handle expiration etc.
scunliffe