GUID(Globally Unique Identifier,全球唯一標識符),又稱 UUID(Universally Unique Identifier)。它是一個 128 位(16 字節)的二進制數值,通常以 32 位十六進制字符表示,格式為 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx(8-4-4-4-12 分組),例如:6F9619FF-8B86-D011-B42D-00C04FC964FF。
適合簡單場景,無依賴,代碼極簡:
<?php
function create_guid(): string {
// 1. 獲取高熵值隨機字符串:微秒時間 + 高精度隨機數
$charid = strtoupper(md5(uniqid(mt_rand(), true)));
$hyphen = '-';
// 2. 按 RFC 4122 格式組裝:8-4-4-4-12
$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; // 如 {A1B2C3D4-E5F6-7890-ABCD-EF1234567890}
}
// 使用示例
echo create_guid();
?>
注意:此為簡易實現,非嚴格符合 RFC 4122 版本/變體位規範,但滿足大多數業務唯一性需求。
提供 System、NetAddress、Random、Guid 四個協作類,邏輯更清晰,擴展性更強:
<?php
// guid.class.php
class System {
public static function currentTimeMillis(): string {
list($usec, $sec) = explode(" ", microtime());
return $sec . substr($usec, 2, 3); // 毫秒級時間戳
}
}
class NetAddress {
public $Name = 'localhost';
public $IP = '127.0.0.1';
public static function getLocalHost(): self {
$addr = new self();
$addr->Name = $_ENV['COMPUTERNAME'] ?? 'unknown';
$addr->IP = $_SERVER['SERVER_ADDR'] ?? '127.0.0.1';
return $addr;
}
public function toString(): string {
return strtolower($this->Name . '/' . $this->IP);
}
}
class Random {
public function nextLong(): string {
$sign = rand(0, 1) ? '-' : '';
return $sign
. rand(1000, 9999) . rand(1000, 9999)
. rand(1000, 9999) . rand(100, 999) . rand(100, 999);
}
}
class Guid {
private $valueBeforeMD5;
private $valueAfterMD5;
public function __construct() {
$this->getGuid();
}
private function getGuid(): void {
$address = NetAddress::getLocalHost();
$this->valueBeforeMD5 = $address->toString() . ':' . System::currentTimeMillis() . ':' . (new Random())->nextLong();
$this->valueAfterMD5 = md5($this->valueBeforeMD5);
}
public static function newGuid(): self {
return new self();
}
public function toString(): string {
$raw = strtoupper($this->valueAfterMD5);
return substr($raw, 0, 8) . '-'
. substr($raw, 8, 4) . '-'
. substr($raw, 12, 4) . '-'
. substr($raw, 16, 4) . '-'
. substr($raw, 20, 12); // 標準格式,不含大括號
}
}
?>
<?php
require_once 'guid.class.php';
$guid = Guid::newGuid();
echo $guid->toString(); // 輸出如:A1B2C3D4-E5F6-7890-ABCD-EF1234567890
?>
PHP 7+ 環境下,強烈推薦使用成熟庫 ramsey/uuid,完整支援 RFC 4122 所有版本(v1~v8),且經過大規模生產驗證:
composer require ramsey/uuid
use Ramsey\Uuid\Uuid;
$uuid = Uuid::uuid4()->toString(); // 隨機 UUID v4
$uuid = Uuid::uuid1()->toString(); // 基於時間+MAC 的 UUID v1
$uuid = Uuid::uuid7()->toString(); // 新標準:時間有序 UUID v7(適合資料庫主鍵)
| 維度 | 簡易函數 | 自定義類 | ramsey/uuid |
|---|---|---|---|
| 代碼量 | 極少 | 中等 | 零(Composer 引入) |
| 標準合規 | 非嚴格 | 自定義格式 | 完全符合 RFC 4122 |
| 性能 | 極快 | 良好 | 優化過,生產級 |
| 功能豐富度 | 單一 | 可擴展 | 全版本支援、編碼/解碼、排序優化 |
| 推薦場景 | 舊項目、無 Composer 環境 | 教學、特殊格式需求 | 所有現代 PHP 項目 |
GUID/UUID 是分佈式系統、數據同步、日誌追蹤等場景的基石。理解其生成原理有助於選型,但生產環境請優先採用社區維護的標準庫,避免重複造輪子帶來的隱患。