UUID Generator — PHP source
Generate RFC 4122 v4 UUIDs with crypto-grade randomness. Bulk generate, copy all, toggle format (uppercase / no hyphens).
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* RFC 4122 v4 UUID generator (cryptographically secure).
*
* Language: PHP
* CosmoDev polyglot showcase port of the `uuid` tool.
* Ported from src/lib/uuid.ts — display source, part of CosmoDev's
* polyglot tool pages.
*
* Produces a random (v4) UUID: 36 characters, lowercase, hyphenated as
* 8-4-4-4-12 hex digits, with the RFC version (4) and variant (10xx)
* bits set.
*
* Uses random_bytes() — PHP's CSPRNG backed by the host entropy source
* (getrandom(2) on Linux, CryptGenRandom on Windows). It is the correct
* primitive for any identifier that must be unguessable; never reach for
* mt_rand() or rand() in a security context.
*/
declare(strict_types=1);
/**
* Generate one RFC 4122 version-4 UUID string.
*
* @return string Lowercase 36-char UUID, e.g.
* "f47ac10b-58cc-4372-a567-0e02b2c3d479"
*
* @throws Exception If the host CSPRNG cannot gather sufficient entropy
* (the equivalent of the TypeScript lib's "no crypto" failure).
*/
function uuid_v4(): string
{
// 16 cryptographically secure random bytes. random_bytes() throws
// Exception if the entropy source is unavailable.
$bytes = random_bytes(16);
// version 4: high nibble of byte 6 = 0100
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40);
// variant : high bits of byte 8 = 10 -> next hex digit is 8-b
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
// bin2hex doubles the length (1 byte -> 2 lowercase hex chars).
$hex = bin2hex($bytes);
// Slice into the canonical 8-4-4-4-12 groups.
return substr($hex, 0, 8)
. '-' . substr($hex, 8, 4)
. '-' . substr($hex, 12, 4)
. '-' . substr($hex, 16, 4)
. '-' . substr($hex, 20, 12);
}
// CLI demo: `php uuid.php` prints one UUID.
echo uuid_v4(), PHP_EOL;
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →