PHP random_bytes() and random_int()
PHP provides random_bytes() and random_int() for cryptographically secure random values.
Generate Random Bytes
$token = bin2hex(random_bytes(32));
This produces 32 random bytes represented as a hexadecimal string. It can be useful for generating high-entropy tokens, provided the token is stored and validated securely.
Generate a Secure Random Integer
$number = random_int(100000, 999999);
random_int() chooses an integer in the inclusive range using a cryptographically secure source.
Do Not Use rand() for Security Tokens
General-purpose pseudo-random functions are not appropriate for password reset tokens, authentication secrets, or other security-sensitive values. Use the cryptographically secure functions instead.
Handle Failures
These functions can throw an exception if a secure random source is unavailable. Handle failures at an appropriate application boundary; do not silently fall back to a weak generator.
Summary
Use random_bytes() for secure random byte strings and random_int() for secure random integers. Choose a sufficient length and protect generated tokens throughout their lifecycle.