How to Generate Unique IDs in PHP with uniqid
This article explains how to generate unique identifier strings in
PHP using the built-in uniqid() function. You will learn
the basic syntax of the function, how to use prefixes, how to increase
ID entropy for better collision resistance, and the security limitations
you should keep in mind during development.
Basic Usage of uniqid()
The uniqid() function in PHP generates a unique
identifier based on the current system time in microseconds. By default,
it returns a 13-character hexadecimal string.
Here is the simplest way to use it:
<?php
$unique_id = uniqid();
echo $unique_id;
// Example output: 65f3a2b1c0e4d
?>Because this value is based on the system clock, generating multiple IDs in rapid succession on highly active servers can occasionally result in duplicate values.
Adding a Prefix
You can pass a prefix as the first argument to uniqid().
This is useful if you are generating IDs for different types of
resources (e.g., users, orders, or files) and want to distinguish them
easily.
<?php
$user_id = uniqid('user_');
$order_id = uniqid('order_');
echo $user_id; // Example output: user_65f3a2b1c0e4d
echo $order_id; // Example output: order_65f3a2b1c0e4d
?>Adding a prefix also reduces the chance of collision if IDs are generated at the exact same microsecond on different servers.
Increasing Entropy for Better Uniqueness
To make the generated ID more unique, you can set the second
parameter, $more_entropy, to true.
When this parameter is enabled, PHP appends additional entropy (using a combined linear congruential generator) to the end of the string. This changes the output from 13 characters to a 23-character string containing a dot.
<?php
$more_unique_id = uniqid('', true);
echo $more_unique_id;
// Example output: 65f3a2b1c0e4d.89416527
?>Combined with a prefix, this is the safest way to use
uniqid():
<?php
$secure_id = uniqid('prefix_', true);
echo $secure_id;
// Example output: prefix_65f3a2b1c0e4d.89416527
?>Security Warning: Do Not Use for Cryptography
The uniqid() function does not generate
cryptographically secure values. Because it relies heavily on system
time, the output is predictable.
- Do use
uniqid()for: Database keys, temporary file names, CSS/JS cache-busting query strings, or session identifiers where security is not a concern. - Do NOT use
uniqid()for: Password reset tokens, API keys, CSRF tokens, or encryption keys.
For cryptographically secure random strings, use
random_bytes() or
openssl_random_pseudo_bytes() instead.