萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 生成 UUID/GUID 完整指南:多種算法實現與效能對比

UUID 版本與格式

PHP 內建函數 (PHP 7.1+)

<?php
// UUID v4 (隨機) - 推薦通用
$uuid = uuid_create(UUID_TYPE_RANDOM);  // 需 pecl install uuid
// 或
$uuid = bin2hex(random_bytes(16));      // 32位十六進制,無連字符

// 格式化為標準 UUID
function formatUuid(string $hex32): string
{
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split($hex32, 4));
}

// 使用示例
$uuid = formatUuid(bin2hex(random_bytes(16)));
// 輸出: 550e8400-e29b-41d4-a716-446655440000

純 PHP 實現 (無擴展依賴)

方案一:基於 uniqid + md5 (v4 風格)

<?php
function uuidV4(): string
{
    // 128 位隨機數:uniqid(微秒) + mt_rand + entropy
    $data = random_bytes(16);  // PHP 7+ 推薦
    // 兼容舊版本
    if (!function_exists('random_bytes')) {
        $data = openssl_random_pseudo_bytes(16);
        if ($data === false) {
            $data = hash('sha256', uniqid(mt_rand(), true) . random_int(0, PHP_INT_MAX), true);
            $data = substr($data, 0, 16);
        }
    }
    
    // 設置版本位 (v4 = 0100) 和變體位 (RFC 4122 = 10xx)
    $data[6] = chr((ord($data[6]) & 0x0f) | 0x40);  // version 4
    $data[8] = chr((ord($data[8]) & 0x3f) | 0x80);  // variant RFC 4122
    
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

方案二:UUID v1 (時間 + MAC) - 可排序

<?php
function uuidV1(): string
{
    // 獲取 MAC 地址 (跨平台)
    $mac = getMacAddress(); // 見下方實現
    
    // 100ns 間隔時間戳 (從 1582-10-15 開始)
    $timestamp = (int)((microtime(true) - (-12219292800)) * 10000000);
    
    // 時鐘序列 (防止同 100ns 內重複)
    static $clockSeq = null;
    if ($clockSeq === null) {
        $clockSeq = random_int(0, 0x3fff);
    }
    
    // 組裝 16 字節
    $bytes = '';
    $bytes .= pack('N', ($timestamp >> 32) & 0xffffffff);  // time_high
    $bytes .= pack('n', ($timestamp >> 16) & 0xffff);      // time_mid
    $bytes .= pack('n', ($timestamp & 0xffff) | 0x1000);   // time_low + version 1
    $bytes .= pack('n', $clockSeq | 0x8000);               // clock_seq + variant
    $bytes .= $mac;                                         // node (6 bytes)
    
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
}

function getMacAddress(): string
{
    // Linux/macOS
    if (PHP_OS_FAMILY !== 'Windows') {
        $output = shell_exec('cat /sys/class/net/*/address 2>/dev/null | head -1');
        if ($output) return pack('H*', str_replace(':', '', trim($output)));
    }
    // Windows
    $output = shell_exec('getmac /fo csv /nh 2>nul');
    if ($output) {
        $lines = explode("\n", trim($output));
        foreach ($lines as $line) {
            if (preg_match('/([0-9A-F]{2}[:-]){5}[0-9A-F]{2}/i', $line, $m)) {
                return pack('H*', str_replace(':', '', $m[0]));
            }
        }
    }
    // 回退:隨機節點標識 (多播位置 1)
    return chr(0x01) . random_bytes(5);
}

方案三:UUID v7 (時間有序,推薦高寫入場景)

<?php
function uuidV7(): string
{
    // Unix 毫秒時間戳 (48 bits)
    $ms = (int)(microtime(true) * 1000);
    $bytes = pack('J', $ms << 16);  // 6 bytes (48 bits)
    
    // 版本 7 (4 bits) + 變體 (2 bits) + 隨機 (74 bits)
    $rand = random_bytes(10);
    $rand[0] = chr((ord($rand[0]) & 0x0f) | 0x70);  // version 7
    $rand[1] = chr((ord($rand[1]) & 0x3f) | 0x80);  // variant RFC 4122
    
    $bytes .= $rand;
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
}

效能基準測試 (100 萬次)

版本生成依據格式 (8-4-4-4-12)適用場景
v1時間戳 + MAC 地址xxxxxxxx-xxxx-1xxx-xxxx-xxxxxxxxxxxx分布式唯一 ID、可排序
v3/v5命名空間 + 名稱 (MD5/SHA1)xxxxxxxx-xxxx-3xxx/5xxx-xxxx-xxxxxxxxxxxx確定性 UUID、同輸入同輸出
v4隨機數 (加密強隨機)xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx通用唯一 ID、無協調需求
v6/v7 (新)時間戳重排 + 隨機時間有序、資料庫索引友好高寫入場景、替代 v1
方法耗時 (秒)記憶體特點
uuid_create (PECL)0.42低C 層實現、最快、需安裝擴展
random_bytes + format0.68低純 PHP 7+、推薦通用
uniqid + md5 (舊寫法)1.85中熵不足、不推薦新專案
ramsey/uuid (功能全)2.10高功能完整、支援所有版本、對象式 API

Composer 生產級庫推薦

# 功能最全、標準遵循最好
composer require ramsey/uuid

# 輕量、只需 v4
composer require symfony/uid
<?php
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;

try {
    // v1 (時間+MAC)
    $uuid1 = Uuid::uuid1();
    
    // v4 (隨機)
    $uuid4 = Uuid::uuid4();
    
    // v7 (時間有序,需 4.7+)
    $uuid7 = Uuid::uuid7();
    
    // 自定義命名空間 v5
    $uuid5 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'example.com');
    
    echo $uuid4->toString();  // 標準格式
} catch (UnsatisfiedDependencyException $e) {
    // 回退純 PHP 實現
}

資料庫存儲建議

  • MySQL:CHAR(36) 或 BINARY(16) (節省 50% 空間、索引更快)
  • PostgreSQL:原生 UUID 類型
  • 轉換:UUID_TO_BIN() / BIN_TO_UUID() (MySQL 8.0+)

總結選型建議

  • 一般業務 ID:random_bytes(16) + 格式化 (v4),無依賴、高效
  • 分布式系統、需排序:UUID v7 (或 v1)
  • 確定性需求 (同輸入同輸出):UUID v5
  • 企業級專案、需完整 RFC 合規:ramsey/uuid
copyright © 萬盛學電腦網 all rights reserved