This is a short guide on how to generate a random token with PHP. These kind of tokens are used for a number of different reasons:
- To protect against Cross-Site Request Forgery. These are often referred to as CSRF tokens.
- To help verify a user’s email address. i.e. You send the user’s email address a link that contains a “random” token in the URL and when they click on it, you compare the token that they’ve given you with the token that you’ve stored against their user account. If the tokens match, you assume that the given email address is correct.
- To generate a “Forgot Password” request (typically, it uses the same method as the one outlined above).
A lot of people make the mistake of using the function rand or mt_rand in correlation with a hashing function such as md5 or sha1:
$token = sha1(mt_rand(1, 90000) . 'SALT');
The problem with the approach above is that the token will NOT be cryptographically secure.
To generate a cryptographically secure token in PHP, you will need to use the openssl_random_pseudo_bytes function:
//Generate a random string.
$token = openssl_random_pseudo_bytes(16);
//Convert the binary data into hexadecimal representation.
$token = bin2hex($token);
//Print it out for example purposes.
Using Open SSL is far more secure than hashing the results of one of PHP’s random functions!