Sometimes we need to create a random string or token using PHP. For example, it’s quite common that when we want to reset our password on some website a message is sent to the mail we registered.
Probably the message have a link like this:
Where 123 is the token. Today we will see how to create a token cryptographically secure using PHP. We can use this token as a password or as random string to reset something.
This works for PHP 5 and for PHP 7.
Generate cryptographically secure token using PHP
Let’s see how to generate a token in PHP, which is nothing more than a set of characters that should not be guessed in any way (except by brute force, but that’s another story).
There are 2 versions of this script, the first for PHP 5 and the second for PHP 7.
This is because PHP 7 incorporates new functions that are not present in the other versions, so we must look for alternatives.
In PHP 5
If we use PHP in its version 5 (although we should update) this will generate a secure token:
We divide the length between 2, since when representing each byte in hexadecimal format these are converted into 2 digits.
For example, “Hola” in hexadecimal is 48656c6c6f.
And to call it we call it with an argument: the length. That is, how many characters we want or the expected length of the string.
It is important to note that when we pass 7 it actually returns a string of length 6, so we better pass even numbers and greater than 4.
We would modify the function and call
random_bytes instead of
openssl_random_pseudo_bytes. It looks like this:
We can call the function and it will return a random string like this:
Just as seen in the following image: