tags:

views:

45

answers:

2

I'm using uniqid() in PHP to generate a UUID however, the returned string is something like: 4cca63b0d4be4

I thought UUIDs are suppose to be something like: 550e8400-e29b-41d4-a716-446655440000

How do you create a UUID in PHP?

Usually I use auto-increment in MySQL to get my unique IDs, however, sometimes I want to generate a UUID when a unique ID needs to be displayed to the user. I don't want users to get a ID for a ticket/reference for example of 1, 2, 3, etc, or even 10222. Not a good idea for users to know how many records there are in my database (to work out how many users I have etc). I'm not using a hash or hashing the UUID since that defeats the purpose of using a UUID, and i have no problems string the 128bit string. What are your comments on the chances of collisions? if i have a million records for example. Also reading on wiki i see there are 5 versions, v1 v2 v3 v4 v5... which one should i use?

A: 

uuid v4:

function gen_uuid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        // 32 bits for "time_low"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

        // 16 bits for "time_mid"
        mt_rand( 0, 0xffff ),

        // 16 bits for "time_hi_and_version",
        // four most significant bits holds version number 4
        mt_rand( 0, 0x0fff ) | 0x4000,

        // 16 bits, 8 bits for "clk_seq_hi_res",
        // 8 bits for "clk_seq_low",
        // two most significant bits holds zero and one for variant DCE1.1
        mt_rand( 0, 0x3fff ) | 0x8000,

        // 48 bits for "node"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
}

Taken from here.

Gabi Purcaru
thanks! I did see that, is it reliable? seems to be a bit of a hack?
cappuccino
Also, which version should I use? v1 2 3 4 or 5?
cappuccino
@cappuccino why wouldn't it? it is based on the UUID v4 definition, so it has to be ok http://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29
Gabi Purcaru
If you ask me, any of them would be OK. Read this http://en.wikipedia.org/wiki/Universally_unique_identifier#Random_UUID_probability_of_duplicates about duplicate UUID's
Gabi Purcaru
wow, fantastic! does that take into account the birthday paradox? I've read up on all this stuff about the birthday paradox saying that collision is more likely than people think?
cappuccino
of course it does
Gabi Purcaru
A: 

While I cannot answer the question on how to create UUIDs in PHP, the question about collisions is an often-asked one on StackOverflow. See for example Are GUID collisions possible?.

In short, collisions are not mathematically impossible, but are sufficiently improbable to be as good as impossible.

DocMax