您的当前位置:首页>全部文章>文章详情

PHP基于版本4格式生成UUID

发表于:2023-04-23 17:19:07浏览:680次TAG: #UUID

PHP中生成UUID的函数为com_create_guid(),该函数返回一个版本4格式的UUID字符串。

该函数在Windows系统中使用COM库生成UUID,在Linux系统中使用内置的uuid_create()函数实现。对于不支持COM库的系统,可以使用如下方式模拟生成UUID:

function get_uuid() {
    if (function_exists('com_create_guid') === true)
        return trim(com_create_guid(), '{}');
    else {
        $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));
    }
}

 

仅支持PHP7