PHP生成随机文件名有多种方式,本次介绍一个在公认比较新、比较安全的随机ID函数。较老的方式一般单一使用rand函数生成随机数字,或者用md5,或者进一步使用uniqid()函数,但不论以上哪种方式,都存在可能重复的问题。我查阅了国外技术论坛,总结了一个名为unique_ID的函数,采用了目前公认较为安全、不容易出现重复的写法,优先使用random_bytes函数、openssl_random_pseudo_byte函数进行随机字符生成。
此函数可以用在各类需要生成唯一ID的场景中,一个非常普遍的场景就是上传图片名。
/**
* unique_ID
* 生成16位以上唯一ID
*
* @author Aspirant Zhang
* @param int $length 不含前缀的长度,最小16,建议20+
* @param str $prefix 前缀
* @return str $id
*/
function unique_ID($length = 16,$prefix = ''){
$id = $prefix;
$addLength = $length - 13;
$id .= uniqid();
if (function_exists('random_bytes')) {
$id .= substr(bin2hex(random_bytes(ceil(($addLength) / 2))),0,$addLength);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$id .= substr(bin2hex(openssl_random_pseudo_bytes(ceil($addLength / 2))),0,$addLength);
} else {
$id .= mt_rand(1*pow(10,($addLength)),9*pow(10,($addLength)));
}
return $id;
}