生成唯一文件名、订单号、邀请码、临时密码、API 签名 nonce 等,核心需求:唯一性、不可预测性、性能。
<?php
$fileId = date('Ymd-His') . '-' . rand(100, 999);
// 例: 20240115-143022-874
?>
<?php
function randomKeys(int $length): string {
$pool = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$max = strlen($pool) - 1;
$result = '';
for ($i = 0; $i < $length; $i++) {
$result .= $pool[mt_rand(0, $max)];
}
return $result;
}
echo randomKeys(16); // 例: aB3fK9zL2mN8pQ1x
?>
mt_rand 比 rand 速度快、周期长 (2^31-1)。<?php
// 自定义种子函数 (微秒时间)
function seed(): float {
list($msec, $sec) = explode(' ', microtime());
return (float)$sec + (float)$msec;
}
srand(seed()); // 设置种子
echo rand(10, 100); // 同种子下每次运行结果固定
?>
srand() 设定种子后,rand() 序列完全确定。<?php
// PHP 7+ 推荐
$bytes = random_bytes(16); // 16 字节二进制
$token = bin2hex($bytes); // 32 位十六进制
$base64 = base64_encode($bytes); // URL 安全 Base64
// 整数范围 (PHP 7+)
$secureInt = random_int(100000, 999999); // 6 位数字验证码
?>
| 函数 | 用途 | 安全性 |
|---|---|---|
| random_bytes() | 生成任意长度加密安全字节串 | ✅ CSPRNG |
| random_int() | 生成范围内加密安全整数 | ✅ CSPRNG |
| mt_rand() | 高性能伪随机 | ❌ 可预测 |
| rand() | 旧版伪随机 | ❌ 可预测 |
| uniqid('', true) | 微秒时间+熵 (非加密) | ⚠️ 低熵 |
<?php
function generateRandomString(int $length = 32, string $charset = 'alphanumeric'): string {
$pools = [
'numeric' => '0123456789',
'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'alphanumeric' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'safe' => '23456789ABCDEFGHJKLMNPQRSTUVWXYZ', // 去除 0/O/I/l/1
];
$pool = $pools[$charset] ?? $pools['alphanumeric'];
$bytes = random_bytes($length);
$result = '';
$poolLen = strlen($pool);
for ($i = 0; $i < $length; $i++) {
$result .= $pool[$bytes[$i] % $poolLen];
}
return $result;
}
// 用法
echo generateRandomString(16, 'safe'); // 邀请码
echo generateRandomString(32, 'alphanumeric'); // API Secret
?>
uniqid('', true)。generateRandomString(8, 'safe')。random_bytes/int (PHP 7+)。mt_srand($fixedSeed) + mt_rand。