Generating confirmation code for an email confirmation Generating confirmation code for an email confirmation php php

Generating confirmation code for an email confirmation


$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)), 16, 16); // 16 characters long

Alternative methods to generate random data include:

$random_hash = md5(openssl_random_pseudo_bytes(32));$random_hash = md5(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));// New in PHP7$random_hash = bin2hex(random_bytes(32));


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 identifierIt 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
(source: jackborn.com)

$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


The accepted answer suggests using a hash of PHP's uniqid(). The documentation for uniqid explicitly warns that it does not create "random nor unpredictable strings", and states emphatically that "This function must not be used for security purposes."

If there is any concern over the possibility of a confirmation code being guessed (and that is the whole point of issuing a code) you may wish to use a more random generator such as openssl_random_pseudo_bytes(). You can then use bin2hex() to turn it into a nice alphanumeric. The following looks just like the output of John Conde's answer, but is (supposedly) more random and less guessable:

// generate a 16 byte random hex string$random_hash = bin2hex(openssl_random_pseudo_bytes(16))

Late addendum: As Oleg Abrazhaev points out, if you want to make sure your system is actually capable of generating cryptographically strong random values at runtime, openssl_random_pseudo_bytes accepts a reference to a bool to report this. Code from phpinspectionsea docs:

$random = openssl_random_pseudo_bytes(32, $isSourceStrong);if (false === $isSourceStrong || false === $random) {    throw new \RuntimeException('IV generation failed');}

Then use the generated random value as before:

$random_hash = bin2hex($random)