Open In App

PHP | uniqid( ) Function

Improve
Improve
Like Article
Like
Save
Share
Report

The uniqid() function in PHP is an inbuilt function which is used to generate a unique ID based on the current time in microseconds (micro time). 
The ID generated from the uniqid() function is not optimal since it is based on the system time and is not cryptographically secured. Thus it should not be for cryptographical purposes.
The uniqid( ) function accepts prefix and more_entropy as parameters and returns timestamp based unique identifier as a string.
 

Syntax:  

 uniqid($prefix, $more_entropy) 

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

  1. $prefix : It is an optional parameter which specifies a prefix to the unique id. It must be string.
  2. $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: 

  1. The uniqid() function tries to create unique identifier, but it does not guarantee 100% uniqueness of return value.
  2. 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.

Below programs illustrate the uniqid() function:
Program 1: 

php




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


Output:  

3b2c662647f18

Program 2: 

php




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


Output:  

gfg5b2b451823970

Program 3: 

php




<?php
// generating unique id with prefix gfg
// and higher entropy
$myuid = uniqid('gfg', true);
 
echo $myuid;
?>


Output:  

gfg5b2b4555ab6bd7.27884925

Reference : http://php.net/manual/en/function.uniqid.php



Last Updated : 29 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads