Random PHP string

Penleigh Boyd - Spring Fantasy (1919)

I needed to generate a random 32-character hexadecimal string in PHP. In PHP 7 and later, use random_bytes() to generate 16 random bytes and bin2hex() to encode them:

// Generate a random 32-character hexadecimal string.
$string = bin2hex(random_bytes(16));

The original example, md5(time()), was predictable and returned the same value for calls made within the same second. Random values are not guaranteed to be unique; if uniqueness is required, enforce it where the values are stored (for example, with a database unique constraint).

Filed under PHP

Leave a comment

Your email address will not be published. Required fields are marked *