uniqid() function in PHP

The uniqid() function generates a unique ID based on the current time in microseconds. It's commonly used for creating temporary filenames, session IDs, or unique identifiers where collision probability needs to be minimized.

Syntax

uniqid(prefix, more_entropy)

Parameters

  • prefix − Optional string to prefix the unique ID. Default is empty string.

  • more_entropy − Optional boolean. If TRUE, adds additional entropy at the end for better uniqueness. Default is FALSE.

Return Value

The uniqid() function returns a unique identifier as a string, typically 13 characters long (23 characters when more_entropy is TRUE).

Example 1: Basic Usage

Generate a simple unique ID ?

<?php
    echo uniqid();
?>
5bfd5bd045faa

Example 2: With Prefix

Add a prefix to make the ID more descriptive ?

<?php
    echo uniqid('user_');
    echo "<br>";
    echo uniqid('temp_file_');
?>
user_5bfd5bd045fab
temp_file_5bfd5bd045fac

Example 3: With More Entropy

Enable more entropy for enhanced uniqueness ?

<?php
    echo uniqid('', true);
    echo "<br>";
    echo uniqid('session_', true);
?>
5bfd5bd045fad7.23606798
session_5bfd5bd045fae8.34567890

Common Use Cases

  • Creating temporary filenames

  • Generating session identifiers

  • Database record keys (though auto-increment is preferred)

  • Cache keys and unique tokens

Conclusion

The uniqid() function provides a simple way to generate unique identifiers based on timestamp and process ID. Use the more_entropy parameter when higher uniqueness is required, especially in high-traffic applications.

Updated on: 2026-03-15T07:38:13+05:30

389 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements