PHP随机函数【上】

时间:2023-03-09 18:53:23
PHP随机函数【上】

随机函数应用的场景很多,比如验证码,token,订单号等。由浅入深了解常用随机函数

1.rand

常用的随机数字函数,默认生成[0,getrandmax()]之间的随机数(包括边界值),因性能问题已被mt_rand替换。

相关函数:rand(int $min, int $max)生成$min和$max之间的数。

     srand(int $seed) 生成时间种子,同一个时间种子下随机生成的随机值相同。

     getrandmax() 获取最大随机数(随系统不同而不同)。

使用场景:见mt_rand

2.mt_rand

常用随机函数,默认生成[0,mt_getrandmax()]之间的随机函数(包括边界值).

相关函数:mt_rand(int $min, int $max)生成$min和$max之间的数。

     mt_srand(int $seed) 生成时间种子,同一个时间种子下随机生成的随机值相同。

     mt_getrandmax() 获取最大随机数(随系统不同而不同)。

使用场景:生成验证码mt_rand(1000, 9999);

     生成订单号date('YmdHis').str_pad(mt_rand(1,99999), 5, '0', STR_PAD_LEFT);

3.uniqid

生成唯一ID的函数,精确到了微妙,较mt_rand精确。

相关函数:uniqid([string $prefix = "" [, bool $more_entropy = false ]]) 前缀可用在多个脚本生成ID重复问题,正常返回13位,加密后返回23位

使用场景:生成token md5(uniqid())

     生成uuid

function guid(){
if (function_exists('com_create_guid')){
return com_create_guid();
}else{
mt_srand((double)microtime()*);//optional for php 4.2. and up.
$charid = strtoupper(md5(uniqid(rand(), true)));
$hyphen = chr();// "-"
$uuid = chr()// "{"
.substr($charid, , ).$hyphen
.substr($charid, , ).$hyphen
.substr($charid,, ).$hyphen
.substr($charid,, ).$hyphen
.substr($charid,,)
.chr();// "}"
return $uuid;
}
}
echo guid();

4.openssl_random_pseudo_bytes

函数

使用场景:生成token

public static function getRandomString($length = 42)
{
/*
* Use OpenSSL (if available)
*/
if (function_exists('openssl_random_pseudo_bytes')) {
$bytes = openssl_random_pseudo_bytes($length * 2); if ($bytes === false)
throw new RuntimeException('Unable to generate a random string'); return substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length);
} $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; return substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
}

5.linux下

head /dev/urandom | tr -dc a-z0-9 | head -c 20