根據應用場景(訂單號、Session ID、分散式系統節點 ID)選擇適當方法。以下整理常見方案優缺點。
$id = md5(time() . mt_rand(1, 1000000));
長度 32 字元,單機低併發可用,高併發或分散式不推薦。
$id = uniqid(); // 如 5f8d3a1b2c4e6
$id = uniqid('prefix_'); // 加前綴
$id = uniqid('', true); // more_entropy=true,增加熵值
基於微秒時間,同一微秒內多次呼叫可能重複,官方文件建議搭配 md5() 使用。
function generateUuid() {
// Windows 有 com_create_guid,Linux 需自行實作
if (function_exists('com_create_guid')) {
return com_create_guid(); // 含大括號 {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
}
// 手動實作 RFC 4122 v4
$bytes = random_bytes(16);
// 設定版本位元 (4) 與變體位元 (10xx)
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40);
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
}
// 輸出範例:5d2f8a1c-3b7e-4f9a-8c2d-1e6f9a3b7c4d
function createGuid($namespace = '') {
static $guid = '';
$uid = uniqid('', true);
$data = $namespace
. $_SERVER['REQUEST_TIME']
. ($_SERVER['HTTP_USER_AGENT'] ?? '')
. ($_SERVER['LOCAL_ADDR'] ?? '')
. ($_SERVER['LOCAL_PORT'] ?? '')
. ($_SERVER['REMOTE_ADDR'] ?? '')
. ($_SERVER['REMOTE_PORT'] ?? '');
$hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
$guid = '{'
. substr($hash, 0, 8) . '-'
. substr($hash, 8, 4) . '-'
. substr($hash, 12, 4) . '-'
. substr($hash, 16, 4) . '-'
. substr($hash, 20, 12)
. '}';
return $guid;
}
AUTO_INCREMENT 或 SEQUENCE 最簡單可靠。snowflake-php。| 場景 | 推薦方法 | 長度 | 排序性 |
|---|---|---|---|
| 一般 Web 表單 Token | uniqid('', true) / bin2hex(random_bytes(16)) | 32 | 無 |
| API 請求追蹤 ID | UUID v4 | 36 | 無 |
| 訂單號、流水號 | 日期前綴 + 自增/隨機 | 自訂 | 可排序 |
| 分散式服務追蹤 | Snowflake / UUID v7 | 64bit/36 | 可排序 |
| 資料庫主鍵 | BIGINT AUTO_INCREMENT / UUID | - | - |
核心原則:業務可讀性用有意義前綴,高併發用隨機熵,需排序用時間元件,分散式用協調演算法。