DevToolsForYou

UUID Generator in PHP — Code Examples

UUID Generator in PHPUse the online tool →

UUIDs (Universally Unique Identifiers) are 128-bit identifiers used as database primary keys, session tokens, and idempotency keys. UUID v4 (random) is the safe default; UUID v7 (time-ordered) is preferred for database primary keys.

PHP has no built-in UUID function before 8.x. Use ramsey/uuid for full UUID support or generate v4 manually with random_bytes().

PHP (manual v4)
<?php

// UUID v4 — manual implementation using random_bytes()
function uuid_v4(): string {
    $data = random_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // version 4
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // variant bits
    return vsprintf("%s%s-%s-%s-%s-%s%s%s", str_split(bin2hex($data), 4));
}

echo uuid_v4() . "
"; // e.g. 110e8400-e29b-41d4-a716-446655440000
PHP (ramsey/uuid)
<?php
// composer require ramsey/uuid
use RamseyUuidUuid;

// UUID v4 — random
$id = Uuid::uuid4();
echo $id->toString() . "
";

// UUID v7 — time-ordered
$id7 = Uuid::uuid7();
echo $id7->toString() . "
";

// UUID v5 — deterministic
$id5 = Uuid::uuid5(Uuid::NAMESPACE_URL, "https://example.com");
echo $id5->toString() . "
";
Notes & gotchas
  • Use random_bytes() not rand() or mt_rand() — those are not cryptographically secure.
  • ramsey/uuid is the de facto standard PHP UUID library and supports v1 through v8.
  • PHP 8.1 does not add built-in UUID support — a package is still required for anything beyond manual v4.
Try it in your browser

Need to uuid generator without writing code? The UUID Generator runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open UUID Generator
UUID Generator in other languages