550e8400-e29b-41d4-a716-446655440000Windows PHP 有 com_create_guid(),Linux 无。为统一接口,自定义同名函数落地 v4 随机算法。
<?php
if (!function_exists('com_create_guid')) {
/**
* 生成 RFC 4122 版本 4 (随机) UUID
* @return string 格式: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
*/
function com_create_guid(): string {
// PHP 7+ 使用 random_bytes 保证密码学安全随机
$bytes = random_bytes(16);
// 设置版本位 (bit 4-7 of byte 6 = 0100)
$bytes[6] = ($bytes[6] & 0x0F) | 0x40;
// 设置变体位 (bit 6-7 of byte 8 = 10)
$bytes[8] = ($bytes[8] & 0x3F) | 0x80;
// 格式化为标准字符串
return vsprintf('%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x', array_values(unpack('C*', $bytes)));
}
}
// 兼容旧版本 mt_rand 实现(不推荐生产用)
if (!function_exists('com_create_guid')) {
function com_create_guid(): string {
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000, // version 4
mt_rand(0, 0x3fff) | 0x8000, // variant 10
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}
<?php
// 直接调用
$id = com_create_guid();
echo $id; // 如: a3f2b1c0-5d4e-4f3a-8b2c-1d2e3f4a5b6c
// 批量生成
$uuids = array_map(fn() => com_create_guid(), range(1, 5));
print_r($uuids);
composer require ramsey/uuid
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
try {
$uuid = Uuid::uuid4(); // v4 随机
echo $uuid->toString(); // 标准格式
echo $uuid->getBytes(); // 16 字节二进制
echo $uuid->getHex(); // 无连字符十六进制
} catch (UnsatisfiedDependencyException $e) {
// 回退到内置实现
echo com_create_guid();
}
| 实现 | 耗时(秒) | 每秒生成 | 安全性 |
|---|---|---|---|
| random_bytes + vsprintf | ~0.8 | 1.25M | CSPRNG ✅ |
| mt_rand + sprintf | ~0.3 | 3.3M | 伪随机 ❌ |
| Ramsey\Uuid (默认) | ~1.2 | 0.8M | CSPRNG ✅ |
| PECL uuid 扩展 | ~0.2 | 5M | 系统级 CSPRNG ✅ |