PHP function to generate v4 UUID

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

    I'm sure there's a more elegant way to do the conversion from binary to decimal for the 4xxx and yxxx portions. But if you want to use openssl_random_pseudo_bytes as your crytographically secure number generator, this is what I use:

    return sprintf('%s-%s-%04x-%04x-%s',
        bin2hex(openssl_random_pseudo_bytes(4)),
        bin2hex(openssl_random_pseudo_bytes(2)),
        hexdec(bin2hex(openssl_random_pseudo_bytes(2))) & 0x0fff | 0x4000,
        hexdec(bin2hex(openssl_random_pseudo_bytes(2))) & 0x3fff | 0x8000,
        bin2hex(openssl_random_pseudo_bytes(6))
        );
    

提交回复
热议问题