wp_generate_uuid4()
云策文档标注
概述
wp_generate_uuid4() 是 WordPress 中用于生成随机 UUID(版本 4)的函数,返回一个符合标准格式的字符串。该函数基于 mt_rand() 实现,但开发者需注意其潜在的重复生成风险。
关键要点
- 函数生成一个随机 UUID(版本 4),返回 36 字符的字符串,格式为 8-4-4-4-12 的十六进制数字,用连字符分隔。
- UUID 是 128 位值(16 字节),应视为大小写不敏感,函数始终返回小写字符串。
- 由于使用 mt_rand(),在相同种子下可能产生重复 UUID,导致碰撞问题,建议在需要高唯一性时考虑替代方案。
- 函数自 WordPress 4.7.0 版本引入,常用于 WP_Application_Passwords 和 WP_Customize_Manager 等类中。
注意事项
- mt_rand() 的随机性依赖于种子,重复种子会生成相同 UUID,可能引发碰撞,需谨慎使用。
- 用户贡献笔记中提到,可通过 mt_srand() 结合其他参数(如微秒时间、用户 IP)来改善随机性,但这不是官方推荐做法。
原文内容
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. |
Skip to note 3 content
thanasisxan
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:
mt_srand( crc32( serialize( array( microtime( true ), 'USER_IP', 'ETC' ) ) ) );Skip to note 4 content
Philipp Stracker
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-BBCCDDEEFF00is identical to11223344-5566-7788-99aa-bbccddeeff00This function always returns a lower-case string.
To get a 32-character string (same as MD5) you could use: