PHP function to generate v4 UUID

前端 未结 15 1069
眼角桃花
眼角桃花 2020-11-22 03:01

So I\'ve been doing some digging around and I\'ve been trying to piece together a function that generates a valid v4 UUID in PHP. This is the closest I\'ve been able to come

15条回答
  •  渐次进展
    2020-11-22 03:38

    In my search for a creating a v4 uuid, I came first to this page, then found this on http://php.net/manual/en/function.com-create-guid.php

    function guidv4()
    {
        if (function_exists('com_create_guid') === true)
            return trim(com_create_guid(), '{}');
    
        $data = openssl_random_pseudo_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }
    

    credit: pavel.volyntsev

    Edit: to clarify, this function will always give you a v4 uuid (PHP >= 5.3.0).

    When the com_create_guid function is available (usually only on Windows), it will use that and strip the curly braces.

    If not present (Linux), it will fall back on this strong random openssl_random_pseudo_bytes function, it will then uses vsprintf to format it into v4 uuid.

提交回复
热议问题