Generating Unique IDs in PHP

This tutorial explains the technique to generate unique identifiers that are extremely difficult to predict.

We'll be using the following PHP functions to generate the unique identifier:

Use the code below to assign variable "id" the unique value. I'll discuss the code in more detail below.

$id = md5(uniqid(rand(), true));

After running the statement above PHP variable "id" will be assigned a unique 32 characters long value. Here is how it works:

The rand() function will generate a random number between 0 and getrandmax() (>= 32768). The uniqid function will take the random number as input and generate a unique identifier using the random value. After that we are taking the hash of the resultant unique identifier, which will give us a 32 characters (128 bits) long identifier.

A few sample runs gave me the following values:




Did this tutorial help a little? How about buy me a cup of coffee?

Buy me a coffee at

Please feel free to use the comments form below if you have any questions or need more explanation on anything. I do not guarantee a response.

IMPORTANT: You must thoroughy test any instructions on a production-like test environment first before trying anything on production systems. And, make sure it is tested for security, privacy, and safety. See our terms here.