I need to generate a single-use token in PHP. There are two functions available that I can use for this that seem to do the same thing: random_bytes and openssl_random_pseudo_by
openssl_random_pseudo_bytes
is part of the OpenSSL extension, which must be explicitly configured and included in the PHP compilation process and requires external dependencies.
random_bytes
is new in PHP 7 as the native always-available PHP method to generate random bytes, which chooses its internal source of randomness depending on the platform it's on.
The main reason for introducing random_bytes
was that generating pseudo-random data was always a bit of a headache in PHP, requiring developers to be platform-aware and possibly using several different fallback methods depending on which extensions or system-level functions are available. This often led to bugs in individual implementations, which is particularly concerning in security-relevant code. random_bytes
simplifies this by providing one function which is always available and uses the best possible source of randomness available. If you can target PHP 7+ exclusively, it should be your go-to method.