Generates a random UUID (version 4).
Source
function wp_generate_uuid4() {
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff )
);
}
Changelog
Version | Description |
---|---|
4.7.0 | Introduced. |
Sample result: 11223344-5566-7788-99AA-BBCCDDEEFF00
A UUID represents a 128-bit value (16 bytes): It contains four 4-byte digits that are represented in hex notation, and are segmented by 4 “-” symbols. The total length is 36 characters.
The “-” symbols appear after byte 4, byte 6, byte 8 and after byte 10.
Because it’s a hex-value, a UUID should be treated in a case-insensitive manner:
11223344-5566-7788-99AA-BBCCDDEEFF00
is identical to11223344-5566-7788-99aa-bbccddeeff00
This function always returns a lower-case string.
To get a 32-character string (same as MD5) you could use:
It should be noted that using this function to generate uuid’s WILL lead to collisions by creating duplicates, I found out not the fun way.
The function
mt_rand()
used will always produce the same sequence of random numbers given the same seed. So every time a seed is repeated, the same exact UUID is generated.To get around this, you would need to seed it using something else for example: