Generating 100% Reliable Unique String in PHP

PHP natively provides some functions like uniqid() and others that generate unique strings but these functions aren’t reliable as they …

PHP natively provides some functions like uniqid() and others that generate unique strings but these functions aren’t reliable as they are basically based on the microtime and if the uniqueness of the string is vital for your web app’s stability, then uniqid() and other inbuilt functions’ usage in production is a big no. Recently I had to generate a reliable unique string in one of my web apps and I found a helpful answer at StackOverflow. Although the logic of the functions was encouraging me to use them without any worries but still I decided to test the accuracy of the generated strings.

I used a droplet at Digital Ocean to run a 5-day long automated test (via shell) and stored the generated strings in a MySQL database. My plan was to test this against at least 1 million records but I had to stop at ±0.5 million. I believe that this data is more than enough to proof the reliability of the functions.

Before sharing the functions, I want to show the result of my research. Below table shows the number of generated test strings and their uniqueness.

LengthNumber of TestsDuplicatesUniqueness %Reliability
5526725362399.3121Low
105187650100%Moderate
155189210100%High
205165430100%High
505158470100%Very high

You can see that when I asked the function to generate a 5-character long unique string, 3623 duplicates were resulted out of 526725 records. It means that we should never rely on this length and we should use a minimum length of 10 or 15 to be safe. Lengths above 10 (from 10 to 50) didn’t generate any duplicates so I consider length 10 to be safe, 15 and 20 to be safer and 50+ to be the safest.

Here are the two functions that we can use to generate a unique string or the token like I did in my tests as well as I used in my web app project.

P.S: Include both of these functions to your project. You have to use getToken() function to generate the unique string by passing in the desired length.

Keep reading

More >