Skip to content

Instantly share code, notes, and snippets.

@xhit
Last active August 18, 2026 13:44
Show Gist options
  • Select an option

  • Save xhit/83f22ef5e7ab3971f7a35017cc5d31f9 to your computer and use it in GitHub Desktop.

Select an option

Save xhit/83f22ef5e7ab3971f7a35017cc5d31f9 to your computer and use it in GitHub Desktop.
UUIDv7 in PHP
<?php
// uuidv7 see https://www.rfc-editor.org/rfc/rfc9562#name-uuid-version-7
function uuidv7() {
// current timestamp in ms
$timestamp = intval(microtime(true) * 1000);
return sprintf(
'%02x%02x%02x%02x-%02x%02x-%04x-%04x-%012x',
// first 48 bits are timestamp based
($timestamp >> 40) & 0xFF,
($timestamp >> 32) & 0xFF,
($timestamp >> 24) & 0xFF,
($timestamp >> 16) & 0xFF,
($timestamp >> 8) & 0xFF,
$timestamp & 0xFF,
// 16 bits: 4 bits for version (7) and 12 bits for rand_a
random_int(0, 0x0FFF) | 0x7000,
// 16 bits: 4 bits for variant where 2 bits are fixed 10 and next 2 are random to get (8-9, a-b)
// next 12 are random
random_int(0, 0x3FFF) | 0x8000,
// random 48 bits
random_int(0, 0xFFFFFFFFFFFF),
);
}
for ($i = 0; $i < 10; $i++) {
$uuid = uuidv7();
// echo $uuid . PHP_EOL;
if (!preg_match("/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[8-9a-b][0-9a-f]{3}-[0-9a-f]{12}$/m", $uuid)) {
echo $uuid . ' not valid uuidv7';
}
}
@xhit

xhit commented Jun 25, 2024

Copy link
Copy Markdown
Author

test online Working from php 7.3.0 to current 8.5.6

@grrinch

grrinch commented Feb 3, 2026

Copy link
Copy Markdown

Good code, thanks for that! Just a note - it's safer to use random_int() in place of mt_rand()

@xhit

xhit commented Feb 5, 2026

Copy link
Copy Markdown
Author

@grrinch done! also updates the test online link.

Thanks for the catch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment