PHP函数生成v4 UUID

时间:2010-01-11 06:17:11

标签: php function uuid

所以我一直在做一些挖掘,我一直在努力拼凑一个在PHP中生成有效v4 UUID的函数。这是我能够来的最接近的。我在十六进制,十进制,二进制,PHP的按位运算符等方面的知识几乎不存在。此函数生成有效的v4 UUID直到一个区域。 v4 UUID应采用以下形式:

  

XXXXXXXX-XXXX-的 4 XXX-的ý XXX-XXXXXXXXXXXX

其中 y 是8,9,A或B.这是函数失败的地方,因为它不符合它。

我希望在这个领域比我更多的知识的人可以帮我解决这个问题,并帮助我解决这个问题。

功能如下:

<?php

function gen_uuid() {
 $uuid = array(
  'time_low'  => 0,
  'time_mid'  => 0,
  'time_hi'  => 0,
  'clock_seq_hi' => 0,
  'clock_seq_low' => 0,
  'node'   => array()
 );

 $uuid['time_low'] = mt_rand(0, 0xffff) + (mt_rand(0, 0xffff) << 16);
 $uuid['time_mid'] = mt_rand(0, 0xffff);
 $uuid['time_hi'] = (4 << 12) | (mt_rand(0, 0x1000));
 $uuid['clock_seq_hi'] = (1 << 7) | (mt_rand(0, 128));
 $uuid['clock_seq_low'] = mt_rand(0, 255);

 for ($i = 0; $i < 6; $i++) {
  $uuid['node'][$i] = mt_rand(0, 255);
 }

 $uuid = sprintf('%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
  $uuid['time_low'],
  $uuid['time_mid'],
  $uuid['time_hi'],
  $uuid['clock_seq_hi'],
  $uuid['clock_seq_low'],
  $uuid['node'][0],
  $uuid['node'][1],
  $uuid['node'][2],
  $uuid['node'][3],
  $uuid['node'][4],
  $uuid['node'][5]
 );

 return $uuid;
}

?>

感谢任何可以帮助我的人。

15 个答案:

答案 0 :(得分:329)

不是将其分解为单个字段,而是更容易生成随机数据块并更改单个字节位置。您还应该使用比mt_rand()更好的随机数生成器。

根据RFC 4122 - Section 4.4,您需要更改以下字段:

  1. time_hi_and_version(第7个八位字节的4-7位),
  2. clock_seq_hi_and_reserved(第9个八位字节的第6位和第7位)
  3. 所有其他122位应该足够随机。

    以下方法使用openssl_random_pseudo_bytes()生成128位随机数据​​,在八位字节上进行排列,然后使用bin2hex()vsprintf()进行最终格式化。

    function guidv4($data)
    {
        assert(strlen($data) == 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));
    }
    
    echo guidv4(openssl_random_pseudo_bytes(16));
    

    使用PHP 7,使用random_bytes()生成随机字节序列更简单:

    echo guidv4(random_bytes(16));
    

答案 1 :(得分:247)

取自this对PHP手册的评论,您可以使用:

function gen_uuid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        // 32 bits for "time_low"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

        // 16 bits for "time_mid"
        mt_rand( 0, 0xffff ),

        // 16 bits for "time_hi_and_version",
        // four most significant bits holds version number 4
        mt_rand( 0, 0x0fff ) | 0x4000,

        // 16 bits, 8 bits for "clk_seq_hi_res",
        // 8 bits for "clk_seq_low",
        // two most significant bits holds zero and one for variant DCE1.1
        mt_rand( 0, 0x3fff ) | 0x8000,

        // 48 bits for "node"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
}

答案 2 :(得分:104)

使用 composer 依赖项的任何人,您可能需要考虑此库:https://github.com/ramsey/uuid

它没有比这更容易:

Uuid::uuid4();

答案 3 :(得分:16)

在unix系统上,使用系统内核为你生成一个uuid。

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

Samreden https://serverfault.com/a/529319/210994

  

注意!:使用此方法获取uuid实际上确实耗尽了熵池,非常快!我会避免在频繁调用的地方使用它。

答案 4 :(得分:8)

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.

答案 5 :(得分:5)

我的回答基于评论uniqid user comment,但它使用openssl_random_pseudo_bytes函数生成随机字符串,而不是从/dev/urandom读取

function guid()
{
    $randomString = openssl_random_pseudo_bytes(16);
    $time_low = bin2hex(substr($randomString, 0, 4));
    $time_mid = bin2hex(substr($randomString, 4, 2));
    $time_hi_and_version = bin2hex(substr($randomString, 6, 2));
    $clock_seq_hi_and_reserved = bin2hex(substr($randomString, 8, 2));
    $node = bin2hex(substr($randomString, 10, 6));

    /**
     * Set the four most significant bits (bits 12 through 15) of the
     * time_hi_and_version field to the 4-bit version number from
     * Section 4.1.3.
     * @see http://tools.ietf.org/html/rfc4122#section-4.1.3
    */
    $time_hi_and_version = hexdec($time_hi_and_version);
    $time_hi_and_version = $time_hi_and_version >> 4;
    $time_hi_and_version = $time_hi_and_version | 0x4000;

    /**
     * Set the two most significant bits (bits 6 and 7) of the
     * clock_seq_hi_and_reserved to zero and one, respectively.
     */
    $clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved);
    $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2;
    $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000;

    return sprintf('%08s-%04s-%04x-%04x-%012s', $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node);
} // guid

答案 6 :(得分:5)

$uuid = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4));

答案 7 :(得分:3)

受到broofa回答here的启发。

preg_replace_callback('/[xy]/', function ($matches)
{
  return dechex('x' == $matches[0] ? mt_rand(0, 15) : (mt_rand(0, 15) & 0x3 | 0x8));
}
, 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx');

或者如果无法使用匿名函数。

preg_replace_callback('/[xy]/', create_function(
  '$matches',
  'return dechex("x" == $matches[0] ? mt_rand(0, 15) : (mt_rand(0, 15) & 0x3 | 0x8));'
)
, 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx');

答案 8 :(得分:2)

如果您使用CakePHP,则可以使用CakeText类中的方法CakeText::uuid();来生成RFC4122 uuid。

答案 9 :(得分:1)

来自汤姆,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])

答案 10 :(得分:1)

如何使用mysql为你生成uuid?

$conn = new mysqli($servername, $username, $password, $dbname, $port);

$query = 'SELECT UUID()';
echo $conn->query($query)->fetch_row()[0];

答案 11 :(得分:1)

已经搜索了完全相同的内容,并且几乎自己实现了该版本,我认为值得一提的是,如果您是在 WordPress 中进行此操作框架,WP为此具有自己的超级方便功能:

$myUUID = wp_generate_uuid4();

您可以阅读说明和来源here

答案 12 :(得分:1)

Jack's answer上的一些变化,增加了对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));
}

答案 13 :(得分:1)

使用Symfony Polyfill / Uuid
然后,您可以生成uuid作为本机php函数:

$uuid = uuid_create(UUID_TYPE_RANDOM);

有关此内容的更多信息,请参见Symfony blop官方文章-https://symfony.com/blog/introducing-the-new-symfony-uuid-polyfill

答案 14 :(得分:0)

我敢肯定,对于4xxxyxxx部分,有一种更优雅的方法可以从二进制转换为十进制。但是,如果您想将openssl_random_pseudo_bytes用作安全的数字生成器,这就是我要使用的:

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))
    );