Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP uniqid() function

Reference for PHP uniqid(): generate a time-based ID, the prefix and more_entropy arguments, why it is not secure or truly unique and better alternatives.

uniqid() returns a string built from the current time in microseconds, written as hexadecimal. It is handy for temporary file names, log correlation and simple identifiers when you only need values that are unlikely to repeat in one process or on one machine.

It is not random and not secure. PHP pauses a microsecond between calls to keep one process's IDs distinct, but IDs from different processes or servers are not coordinated, and anyone who knows roughly when an ID was made can guess it. For tokens, use random_bytes() or random_int(); for database keys, use a UUID or ULID library, or the database's own sequence.

PHP
<?php
echo uniqid();            // e.g. 65f1c9a8b3e41   (13 hex characters)
echo uniqid("order_");    // e.g. order_65f1c9a8b3e41

Try it

PHP Length, prefix and extra entropy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Collisions and better alternatives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
uniqid(string $prefix = "", bool $more_entropy = false): string
Name Description
$prefix Text placed in front of the ID. Useful to tell kinds of IDs apart, or to reduce collisions between servers.
$more_entropy If true, appends a random-looking number with a decimal point, making the string 23 characters (plus the prefix) instead of 13.

Return value: the ID as a string. Without a prefix it is 13 characters; with $more_entropy it is 23.

Usage notes

  • Not secure. Never use uniqid() for password-reset tokens, session IDs, API keys or anything an attacker must not guess. Use bin2hex(random_bytes(16)).
  • Time-based. The first 8 hex characters are the Unix seconds and the next 5 the microseconds, so IDs sort roughly in creation order within one machine.
  • Collisions are possible across processes or servers that call it in the same microsecond. $more_entropy = true makes this much less likely but does not make it impossible.
  • No guarantee of uniqueness for files: use tempnam() or tmpfile() for temporary files, which create the file atomically.
  • Prefix with care. The prefix is returned as is; do not put user input in it and then use the result as a path.
  • Database keys: prefer auto-increment IDs, UUID v4/v7 or ULIDs from a library; they are standardized and sort or index predictably.