Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to generate a UUID

Short answer

A version 4 UUID is 16 random bytes with two marker fields:

<?php
 
function uuid(): string
{
    $bytes = random_bytes(16);
    $bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40);
    $bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80);
 
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
}
 
echo uuid();

Checking the format

A string is checked with a regular expression:

<?php
 
$pattern = '/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i';
 
var_dump(preg_match($pattern, '3f2b8c1e-9d4a-4c6b-8e21-5a7d9f0b1c2d') === 1);
var_dump(preg_match($pattern, 'not-a-uuid') === 1);

Output:

bool(true)
bool(false)

A ready-made library

Projects with Composer use the ramsey/uuid or symfony/uid package: they support other versions too, including time-ordered version 7 UUIDs.

Functions used in this recipe

  • random_bytes — Returns cryptographically secure random bytes.
  • bin2hex — Converts the bytes of a string to hexadecimal.
  • vsprintf — Formats a string by a template, taking the values as an array.

Thanks for reading!

Donate to the site — we work hard for you.