短 ID 生成:不用自增也不重复
用 random_bytes 生成定长 ID,字符集去掉易混字符,附带冲突概率说明与数据库唯一索引建议。
更新于 2026-10-2819 行代码
PHP
<?php
function short_id(int $len = 10): string
{
$alphabet = '23456789abcdefghjkmnpqrstuvwxyz';
$max = strlen($alphabet) - 1;
$id = '';
for ($i = 0; $i < $len; $i++) {
$id .= $alphabet[random_int(0, $max)];
}
return $id;
}
function uuid4(): string
{
$b = random_bytes(16);
$b[6] = chr((ord($b[6]) & 0x0f) | 0x40);
$b[8] = chr((ord($b[8]) & 0x3f) | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
}