Open In App

PHP uniqid( ) Function

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The uniqid() function in PHP generates a unique identifier based on the current time in microseconds. It creates a string that is highly unlikely to duplicate during execution, making it useful for generating unique tokens, filenames, or session IDs. Optional parameters enhance uniqueness.

Syntax

 uniqid($prefix, $more_entropy) 

Parameters Used: The uiqid() function in PHP accepts two parameters. 

  • $prefix : It is an optional parameter which specifies a prefix to the unique id. It must be string.
  • $more_entropy : It is an optional parameter which specifies more entropy at the end of the return value which makes the id more unique.The default value is FALSE, which returns 13 characters long string whereas when it is set to TRUE, the return string is 23 characters long.

Return Value: It returns timestamp based unique identifier as a string.

Errors And Exceptions: 

  • The uniqid() function tries to create unique identifier, but it does not guarantee 100% uniqueness of return value.
  • Since most systems adjust system clock by NTP or like, system time is changed constantly. Therefore, it is possible that this function does not return unique ID for the process/thread.

Example: In this example we generates a unique identifier using the uniqid() function. The output is a string based on the current time in microseconds, which helps create unique IDs for various purposes.

php
<?php
// generating unique id
echo uniqid(); 
?>

Output
66f28d46f08d6

Example 2: In this example we generates a unique identifier using the uniqid() function with a prefix “gfg”. The result is a unique string starting with “gfg”, followed by a timestamp-based unique identifier.

php
<?php
// generating unique id with prefix gfg
$myuid = uniqid('gfg');

echo $myuid;
?>

Output
gfg66f28d652e57a


Next Article

Similar Reads