random_bytes
Returns cryptographically secure random bytes.
Syntax
random_bytes(int $length): stringParameters
| Parameter | Type | Description |
|---|---|---|
| $length | int | The number of bytes. |
Return value
stringA string of random bytes.
Examples
A token of 32 hexadecimal characters — a new one every time:
<?php
echo bin2hex(random_bytes(16));The length of a token:
<?php
echo strlen(bin2hex(random_bytes(16)));Output:
32Notes
The bytes themselves are unprintable, so bin2hex() turns them into text. This is how CSRF tokens, password reset links and random file names are made.
See also
- random_int — Returns a random integer from a range.
- hash — Returns the hash of a string using a chosen algorithm.
- uniqid — Returns an identifier based on the current time.
Related recipes
In the tutorial
- Security — The basics of PHP site security — XSS and escaping, SQL injection, password hashing, CSRF tokens and validating input.