文件
yjyf/server/extend/fast/Random.php
MiAn 62150d261a fix(auth): 修复师傅端上传身份证报请先登录错误与PHP8兼容性
- 修复 addons/cos/library/Auth.php 仅校验用户端登录态导致师傅端Token被误拒的问题,支持MasterAuth多端鉴权
- 增强 api/controller/Common.php upload 方法获取 token 支持 header 读取
- 优化 fast/Random.php uuid 方法采用RFC4122原生random_bytes实现,规避PHP8.4+下Ramsey\\Uuid可空参数弃用异常
2026-11-24 15:46:54 +08:00

110 行
2.7 KiB
PHP
可执行文件

<?php
namespace fast;
use Ramsey\Uuid\Uuid;
/**
* 随机生成类
*/
class Random
{
/**
* 生成数字和字母
*
* @param int $len 长度
* @return string
*/
public static function alnum(int $len = 6): string
{
return self::build('alnum', $len);
}
/**
* 仅生成字符
*
* @param int $len 长度
* @return string
*/
public static function alpha(int $len = 6): string
{
return self::build('alpha', $len);
}
/**
* 生成指定长度的随机数字
*
* @param int $len 长度
* @return string
*/
public static function numeric(int $len = 4): string
{
return self::build('numeric', $len);
}
/**
* 生成指定长度的无0随机数字
*
* @param int $len 长度
* @return string
*/
public static function nozero(int $len = 4): string
{
return self::build('nozero', $len);
}
/**
* 能用的随机数生成
* @param string $type 类型 alpha/alnum/numeric/nozero/unique/md5/encrypt/sha1
* @param int $len 长度
* @return string
*/
public static function build(string $type = 'alnum', int $len = 8): string
{
switch ($type) {
case 'alpha':
case 'alnum':
case 'numeric':
case 'nozero':
switch ($type) {
case 'alpha':
$pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'alnum':
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'numeric':
$pool = '0123456789';
break;
case 'nozero':
$pool = '123456789';
break;
}
return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len);
case 'unique':
case 'md5':
return md5(uniqid(mt_rand()));
case 'encrypt':
case 'sha1':
return sha1(uniqid(mt_rand(), true));
}
}
/**
* 获取全球唯一标识
* @return string
*/
public static function uuid(): string
{
try {
$data = random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
} catch (\Throwable $e) {
return Uuid::uuid4()->toString();
}
}
}