PHP function to generate v4 UUID

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

    From tom, on http://www.php.net/manual/en/function.uniqid.php

    $r = unpack('v*', fread(fopen('/dev/random', 'r'),16));
    $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        $r[1], $r[2], $r[3], $r[4] & 0x0fff | 0x4000,
        $r[5] & 0x3fff | 0x8000, $r[6], $r[7], $r[8])
    
    0 讨论(0)
  • 2020-11-22 03:34

    If you use CakePHP you can use their method CakeText::uuid(); from the CakeText class to generate a RFC4122 uuid.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 03:39

    Anyone using composer dependencies, you might want to consider this library: https://github.com/ramsey/uuid

    It doesn't get any easier than this:

    Uuid::uuid4();
    
    0 讨论(0)
  • 2020-11-22 03:41

    Use Symfony Polyfill / Uuid
    Then you can just generate uuid as native php function:

    $uuid = uuid_create(UUID_TYPE_RANDOM);
    

    More about it, read in official Symfony blop post - https://symfony.com/blog/introducing-the-new-symfony-uuid-polyfill

    0 讨论(0)
  • 2020-11-22 03:42

    on unix systems, use the system kernel to generate a uuid for you.

    file_get_contents('/proc/sys/kernel/random/uuid')
    

    Credit Samveen on https://serverfault.com/a/529319/210994

    Note!: Using this method to get a uuid does in fact exhaust the entropy pool, very quickly! I would avoid using this where it would be called frequently.

    0 讨论(0)
提交回复
热议问题