PHP function to generate v4 UUID

前端 未结 15 1339
眼角桃花
眼角桃花 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:43

    A slight variation on Jack's answer to add support for PHP < 7:

    // Get an RFC-4122 compliant globaly unique identifier
    function get_guid() {
        $data = PHP_MAJOR_VERSION < 7 ? openssl_random_pseudo_bytes(16) : random_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));
    }
    

提交回复
热议问题