UUID in PHP

PHP UUID Generator

PHP has no UUID function, only a random byte source — so the value is assembled by hand, and getting the version nibble right is the whole trick.

random_bytes()RFC 9562 correctOr ramsey/uuid

Generated locally with the Web Crypto API — nothing leaves your browser.

Generating UUIDs in PHP

How to generate

  1. Press Generate UUID above to mint a value in this browser — nothing is sent anywhere.
  2. Copy one value with Copy, or set How many and use Copy all for a fixture list.
  3. Switch Version if your code needs v7 instead of the v4 default, and turn on Formatting to match your stack's conventions.

Use Cases

How PHP UUID Generator Compares

random_bytes(16)CSPRNG; pair it with the version/variant bytes yourself
ramsey/uuidAll versions, parsing and validation, well maintained
uniqid() / rand()Predictable and time-based — never for identifiers you rely on

Code Examples

PHP
<?php
// A v4 UUID from 16 random bytes, with the RFC 9562 bits set
$b = random_bytes(16);
$b[6] = chr((ord($b[6]) & 0x0f) | 0x40); // version 4
$b[8] = chr((ord($b[8]) & 0x3f) | 0x80); // RFC variant

$uuid = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
echo $uuid; // 8f2c7b41-0d3e-4a55-b6c1-8e7d9f0a1b2c
With ramsey/uuid
<?php
// composer require ramsey/uuid
use Ramsey\Uuid\Uuid;

$id = Uuid::uuid4()->toString();   // v4
$v7 = Uuid::uuid7()->toString();   // v7, time-ordered (ramsey/uuid 4.7+)

Frequently Asked Questions

Does PHP have a built-in UUID function?
No. random_bytes() provides the entropy; either assemble the UUID yourself (setting the version and variant bytes) or use the ramsey/uuid package.
Why is my hand-made UUID rejected by validators?
Because the version and variant nibbles were not set. Byte 6 must have 4 in its high nibble and byte 8 must have its top two bits set to 10.
Can I use uniqid() for a UUID?
No. uniqid() is derived from the system clock, so values are predictable and collide under concurrency. Use random_bytes().

Related tools