Generate an unique ID with PHP
Wednesday, June 30th, 2010 | Author:

While creating a webshop I had to generate some unique IDs for market orders. The autoincrement numeric ID is simply not good enough, because someone (for example your competition) could track the number of your orders. So I had to create a simple system to apply some unique ID number to every order that would not reveal how many orders we had so far.

I quickly realised that the md5 hash is too long, because the order code should be much shorter to use it on documents.

The only unique value, I could imagine, is time. If I write a php time() value it is already unique and will never repeat again. Of course you could have two or more orders in the same second of time, so it has to be more specific.

Here is my function:

function uniqueID(){

$time = microtime(1);
$parts = explode(‘.’, (string)$time);
return strtoupper(strrev(dechex($parts[0]) . dechex($parts[1]))) . dechex(rand());

}

//Returns for example 75020CB2C417f

I tested it with this loop:

for($i = 0; $i < 100; $i++){
$array[] = uniqueID();
}

and the $array was always unique! Of course all 100 unique IDs were generated in the same milisecond, but the rand() function ensures that you have no duplicates. I used the dechex() to get shorter results and strrev() to ensure that the result is not so obvious.

The rest is up to you. You should also try to insert some dashes to get more “document look” number, for example 75-020CB2C4-17f. And even if somebody could crack this unique ID, the only result would be the exact time of the order and nothing more!

Category: Web development  | Tags: ,