$str = uniqid(mt_rand(), true); // 微秒時間 + 隨機前綴 + 更多熵
echo 'SHA1: ' . sha1($str) . "
";
echo 'MD5: ' . md5($str) . "
";
uniqid() 基於微秒時間,`mt_rand()` 增加隨機性,`true` 參數啟用更多熵$codes = [];
$prefix = 'CODE';
$total = 1000;
while (count($codes) < $total) {
$key = $prefix . md5(uniqid(mt_rand(), true));
$codes[$key] = null; // 鍵值去重
}
print_r(array_keys($codes));
符合 RFC 4122 格式:xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
function generateGUID() {
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0x4000, 0x4fff), // 版本 4
mt_rand(0x8000, 0xbfff), // 變體 10xx
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
echo generateGUID(); // 如:a3f2b1c4-5678-4abc-9def-123456789abc
function cryptoRandom($bytes = 16) {
return bin2hex(random_bytes($bytes));
}
echo cryptoRandom(16); // 32 字符十六進制,128 位熵
| 方案 | 長度 | 唯一性 | 安全性 | 適用場景 | PHP 版本 |
|---|---|---|---|---|---|
| uniqid+mt_rand+hash | 32/40 | 極高 | 中 | 訂單號、臨時文件、一般 Token | 5.0+ |
| GUID (RFC4122) | 36 | 極高 | 中 | 分布式 ID、數據庫 PK、跨系統追蹤 | 5.0+ |
| random_bytes | 可變 | 理論唯一 | **高(CSPRNG)** | Session、API Key、加密鹽、OAuth state | 7.0+ |
| UUID v1 (時間+MAC) | 36 | 高 | 低 | 需時間排序、機器標識場景 | 需擴展 |
uniqid() 無參數:同微秒內重複概率高rand() 代替 mt_rand():隨機質量差、可預測md5(time()):極易碰撞、可預測random_bytes() 或 openssl_random_pseudo_bytes()// 通用業務 ID
function genBizId($prefix = '') {
return $prefix . md5(uniqid(mt_rand(), true));
}
// 安全 Token
function genSecureToken($bytes = 32) {
return bin2hex(random_bytes($bytes));
}
// 分布式唯一 ID(Snowflake/UUID v1 需擴展)
// 推薦使用成熟庫:ramsey/uuid, sony/flake