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 wa
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)