UUID(Universally Unique Identifier)是一種無需中央協調即可在任意計算機生成的唯一標識符。其值域極大,號稱給地球上每粒沙子分配一個也不會重複。UUID 共有 5 個版本,Version 4 基於隨機數生成,實現最簡單,適用於大多數業務場景。
Windows 版 PHP 提供 com_create_guid()(調用 COM 的 CreateGuid),但 Linux 環境缺少對應擴展。為了代碼跨平台復用,需自行實現同名函數。
if (!function_exists('com_create_guid')) {
function com_create_guid() {
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, // 版本位固定為 4
mt_rand(0, 0x3fff) | 0x8000, // 變體位固定為 10xx
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}
關鍵點:
mt_rand 生成高質量隨機數。0100(Version 4)。10(RFC 4122 變體)。直接調用 com_create_guid() 即可獲得標準格式 UUID 字符串,例如 a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d。無需額外擴展,Windows/Linux 均可運行。