GUID(Globally Unique Identifier)/ UUID(Universally Unique Identifier)是分散式系統、資料庫主鍵、追蹤 ID 的標準選擇。本文提供兩種實現(函數版、類版),解析 RFC 4122 版本 4(隨機)算法,並給出生產級封裝建議。
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx │ │ │ │ │ │ │ └ Variant (bit 6-7): 10xx (RFC 4122) │ │ └ Version (bit 12-15): 0100 = Version 4 (Random) │ └ Time Hi └ Time Low
function generateGuidV4(): string {
// 16 位元組隨機數據
$bytes = random_bytes(16);
// 設定 Version (4) 與 Variant (RFC 4122)
$bytes[6] = chr(($bytes[6] & 0x0f) | 0x40); // Version 4
$bytes[8] = chr(($bytes[8] & 0x3f) | 0x80); // Variant 10x
// 格式化為 8-4-4-4-12
return vsprintf('%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x', array_values(unpack('C*', $bytes)));
}
// 使用
echo generateGuidV4(); // 例: 6f9619ff-8b86-4011-b42d-00c04fc964ff
class Guid {
private string $value;
public function __construct(string $guid = '') {
$this->value = $guid ?: self::generateV4();
}
public static function generateV4(): string {
$bytes = random_bytes(16);
$bytes[6] = chr(($bytes[6] & 0x0f) | 0x40);
$bytes[8] = chr(($bytes[8] & 0x3f) | 0x80);
return vsprintf('%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x', array_values(unpack('C*', $bytes)));
}
// Version 3/5: 命名空間 + 名稱 (MD5/SHA1)
public static function generateV3(string $namespace, string $name): string { /* MD5 實現 */ }
public static function generateV5(string $namespace, string $name): string { /* SHA1 實現 */ }
public function __toString(): string {
return $this->value;
}
public function getBytes(): string {
return pack('H*', str_replace('-', '', $this->value));
}
public function equals(Guid $other): bool {
return $this->value === $other->value;
}
}
// 使用
$guid = new Guid();
echo $guid; // 自動生成 V4
$guid2 = new Guid('6f9619ff-8b86-4011-b42d-00c04fc964ff'); // 解析現有
原文類版採用「主機名 + 微秒時間 + 隨機數」→ MD5 → 格式化。缺點:
建議棄用,改用 `random_bytes()` 版本。
| 實現 | 隨機源 | 加密安全 | RFC 4122 合規 | 相對速度 |
|---|---|---|---|---|
| random_bytes + 位操作 | CSPRNG (OS) | 是 | Version 4 完全合規 | 1.0x (基準) |
| mt_rand + md5 (舊類版) | Mersenne Twister | 否 | 不合規 | 0.7x |
| uniqid(mt_rand(), true) + md5 (舊函數版) | 時間 + mt_rand | 否 | 不合規 | 0.6x |
| com_create_guid() (Windows COM) | OS RPC | 是 | Version 1 (時間+MAC) | 5x 慢 |