Skip to main content

How to Generate a Random Hex String in PHP with random_bytes and bin2hex

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

bin2hex(random_bytes(16)) makes a random hexadecimal string in PHP: 16 random bytes written as 32 characters, such as d9cb569213be972b14f0f09cc7a3fbd3. It's the usual way to make a unique, unguessable ID, because PHP has no built-in UUID function.

Syntax​

Syntax
$<text> = bin2hex(random_bytes(<length>));
PartWhat it does
random_bytes(<length>)Returns <length> random bytes, as a string that's usually unprintable.
bin2hex(...)Writes each byte as two hexadecimal characters, so the result is twice as long.
<length>How many random bytes you want. 16 bytes is 128 bits.

The PHP manual for random_bytes: it "Generates a string containing uniformly selected random bytes with the requested length", and "The randomness generated by this function is suitable for all applications, including the generation of long-term secrets, such as encryption keys." bin2hex "Returns an ASCII string containing the hexadecimal representation of string."

The Example​

The example makes 16 random bytes and prints their length, writes them as hexadecimal and prints that and its length, then makes a second hex string to show it differs.

Prerequisites​

  • PHP 7 or later. This guide uses PHP 8.6.0.

Step 1: Write the Code​

Create a file named main.php:

main.php, which stores random_bytes(16) in bytes and echoes its length, stores bin2hex of it in hex and echoes it and its length, then echoes a second bin2hex(random_bytes(16)).

main.php
<?php

$bytes = random_bytes(16);
echo strlen($bytes) . "\n";

$hex = bin2hex($bytes);
echo $hex . "\n";
echo strlen($hex) . "\n";

echo bin2hex(random_bytes(16)) . "\n";

Step 2: Run It​

Terminal
php main.php
Output
16
d9cb569213be972b14f0f09cc7a3fbd3
32
c8533e1bdcec5609276ffdffee3d6fcf

A zsh terminal where php main.php prints 16, a 32-character hexadecimal string, 32, and a second, different hexadecimal string.

The command is the same in zsh, bash and PowerShell. Your strings will differ, because they're random.

What Happened​

  • random_bytes(16) returned 16 bytes. The script printed their length rather than the bytes themselves, which would show up as garbled characters.
  • bin2hex turned them into 32 characters, two for each byte, using only 0 to 9 and a to f.
  • The second string is different. With 128 random bits, two strings practically never repeat.

That makes it a good ID wherever a UUID would work, for example the jti claim of a JSON Web Token.

Common Mistakes​

MistakeWhat happensDo this instead
Printing or storing random_bytes directlyThe bytes are usually unprintable and can break text and JSONEncode them with bin2hex first
Using mt_rand() for IDs that must not be guessedThe manual warns it "must not be used for cryptographic purposes, or purposes that require returned values to be unguessable"Use random_bytes
Asking for 32 bytes when you want 32 charactersYou get 64 charactersAsk for half as many bytes as characters

Troubleshooting​

SymptomLikely causeFix
The ID is twice as long as expectedbin2hex writes two characters per byteHalve the number passed to random_bytes
ValueError: random_bytes(): Argument #1 ($length) must be greater than 0The length was 0 or negativePass a positive number

FAQ​

Is this a UUID?​

No. It's 32 hexadecimal characters without dashes or a version digit. It's just as hard to guess, and fine wherever any unique string will do.

Does PHP have a UUID function?​

Not in PHP itself. Use bin2hex(random_bytes(16)), or a library if you need the UUID format.

Conclusion​

bin2hex(random_bytes(16)) gives you 32 random hexadecimal characters from a cryptographically secure source, ready to use as an ID or a token.

Additional Resources​