PHP: How to generate a Unique id in PHP (Alphanumeric String)

By Parth Patel on Feb 25, 2020

In php, there are many ways to generate unique alphanumeric id. First of all, we will understand why we might need unique alphanumeric id in first place.

In applications, normally we use unique integer ids which is generally generated by database itself ~ Auto-increment, unique integers. But sometimes we need unique alphanumeric string as ids instead of simple integers.

Few Reasons:

  • Unique ID is needed if you have multiple-server app architecture i.e - Your database is stored in multiple servers
  • If you want to merge different branches of data without clashes
  • Unique ID is helpful and must if you want to prevent sequence discovery of data in application or API endpoints.

Generate Unique Alphanumeric String using uniqid() function in PHP

In PHP, there is a very helpful function uniqid() which generates unique alphanumeric string for you. The function has two parameters ~ though both are optional -

1) $prefix - you can prefix the generated id with any string 2) $more_entropy - By default, it sets to FALSE but if set to TRUE, it will add additional entropy ~ basically it means that it will increase the uniqueness of the returned string

Example:

//generates 13 character random unique alphanumeric id
echo uniqid();
//output - 5e6d873a4f597

//generates 13 character random unique id with prefix - db
echo uniqid("db");
//output - db5e6d875de7ba5

//generates 23 character random unique id with prefix - db but with more randomness
echo uniqid("db",true);
//output - db5e6d8782d90365.80737996

//generates random unique id with random prefix - higher randomness than fixed prefix
echo uniqid (rand (),true);
//output - 5e6d88383c9abdb5e6d88383c9b118314536965e6d88383c9b75.70966391

As you can see above, we can use uniqid() function in different ways to generate unique id.

Generate Unique Alphanumeric String using random_bytes() function in PHP

In PHP 7.x, there is another powerful and more secure function to generate random alphanumeric string - random_bytes(). It requires only one parameter - length, and it generates cryptographically secure pseudo-random bytes. Further, passing its output to another function bin2hex(), will give you unique random string.

Example:

$bytes = random_bytes(16);
echo bin2hex($bytes);
//output - 68309ba352806f9a943e16e74e5a9da3

Thus, using any of the above methods, you can create unique random strings and use it instead of basic integers and thus secure your application. Hope this helped you out.

Adios