UUID/GUID 格式對照
| 標準 | 格式 | 範例 |
| RFC 4122 (標準 UUID) | 8-4-4-4-12 (32 hex + 4 hyphens) | 550e8400-e29b-41d4-a716-446655440000 |
| Microsoft GUID | {8-4-4-4-12} (含大括號) | {550E8400-E29B-41D4-A716-446655440000} |
| ColdFusion CreateUUID() | 8-4-4-16 | 550E8400-E29B-41D4-A716446655440000 |
雙模式實作:優先 COM、備援純 PHP
<?php
function guid(): string
{
// Windows + COM 擴充:呼叫系統 API 產生標準 GUID (含大括號)
if (function_exists('com_create_guid')) {
return com_create_guid(); // 回傳 {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
}
// 純 PHP fallback:以 md5(uniqid(rand(), true)) 產生 32 hex,再格式化
// PHP 4.2+ 不需 mt_srand,但保留相容
mt_srand((double)microtime() * 10000);
$charid = strtoupper(md5(uniqid(rand(), true))); // 32 大寫 hex
$hyphen = '-';
$uuid = '{'
. substr($charid, 0, 8) . $hyphen
. substr($charid, 8, 4) . $hyphen
. substr($charid, 12, 4) . $hyphen
. substr($charid, 16, 4) . $hyphen
. substr($charid, 20, 12)
. '}';
return $uuid; // 格式同 Microsoft GUID
}
?>
現代化替代方案 (PHP 7.1+)
// 1. 引用 ramsey/uuid (業界標準)
use Ramsey\Uuid\Uuid;
$uuid = Uuid::uuid4()->toString(); // 標準 RFC 4122
// 2. PHP 8.2+ Random 類別 (無相依)
$bytes = random_bytes(16);
// 設定 version 4 (random) 與 variant (RFC 4122)
$bytes[6] = ($bytes[6] & 0x0f) | 0x40; // version 4
$bytes[8] = ($bytes[8] & 0x3f) | 0x80; // variant 10x
$uuid = vsprintf('%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x', unpack('C*', $bytes));
// 3. Laravel/Symfony 內建助手
// Laravel: Str::uuid()
// Symfony: Uuid::v4()
效能與隨機性比較
| 方法 | 隨機來源 | 每秒生成量 (估) | 相依性 |
| com_create_guid | Windows RPC (RPCRT4.dll) | ~50,000 | Windows + COM 擴充 |
| md5(uniqid(rand())) | 微秒時間 + mt_rand (非加密安全) | ~200,000 | 無 |
| random_bytes + 格式化 | CSPRNG (OS 級) | ~150,000 | PHP 7+ |
| ramsey/uuid | CSPRNG + 多種版本支援 | ~100,000 | Composer 套件 |
選型建議
- 一般專案:直接 `composer require ramsey/uuid`,標準、安全、功能完整 (v1~v7、有序 UUID、編碼器)。
- 無 Composer 環境 / 輕量需求:使用 `random_bytes` 手刻 RFC 4122 v4,或沿用上述 `guid()` 函式 (注意非加密安全)。
- Windows 專用、需原生 GUID 格式:`com_create_guid()` 最直接。
- 資料庫主鍵:考慮 有序 UUID (ULID/UUIDv7) 減少 B+ 樹分頁分裂,提升寫入效能。
總結
從相容舊版的 `guid()` 到現代 `ramsey/uuid`,PHP 產生 UUID 已有成熟生態。依專案限制選擇:有 Composer 必裝 ramsey/uuid;無 Composer 用 random_bytes 手刻;Windows 獨立專案可用 com_create_guid。