How to generate v4 UUID with PHP?

Spread the love

Sometimes, we want to generate v4 UUID with PHP.

In this article, we’ll look at how to generate v4 UUID with PHP.

How to generate v4 UUID with PHP?

To generate v4 UUID with PHP, we can create our own function.

For instance, we write

function guidv4($data)
{
    assert(strlen($data) == 16);
    $data[6] = chr((ord($data[6]) & 0x0f) | 0x40); 
    $data[8] = chr((ord($data[8]) & 0x3f) | 0x80);

    return vsprintf("%s%s-%s-%s-%s-%s%s%s", str_split(bin2hex($data), 4));
}

echo guidv4(openssl_random_pseudo_bytes(16));

to define the guidv4 function.

We set the value of $data at index 6 and 8 to set the version to 0100 and set bits 6-7 to 10.

And then we call bin2hex eith $data to convert the $data array to hex.

Then we split the string with str_split and poplate the placeholders %s with vsprintf.

Then we call it with the data returned by openssl_random_pseudo_bytes to generaste the uuid.

Conclusion

To generate v4 UUID with PHP, we can create our own function.

Leave a Reply

Your email address will not be published. Required fields are marked *