Last active
September 2, 2024 17:03
-
-
Save xhit/83f22ef5e7ab3971f7a35017cc5d31f9 to your computer and use it in GitHub Desktop.
UUIDv7 in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
mt_rand(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 | |
mt_rand(0, 0x3FFF) | 0x8000, | |
// random 48 bits | |
mt_rand(0, 0xFFFFFFFFFFFF), | |
); | |
} | |
for ($i = 0; $i < 2000000; $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'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
test online