PHP函数生成v4 UUID - PHP function to generate v4 UUID

问题:

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.所以我一直在做一些挖掘,我一直在尝试拼凑一个在 PHP 中生成有效 v4 UUID 的函数。 This is the closest I've been able to come.这是我离得最近的一次。 My knowledge in hex, decimal, binary, PHP's bitwise operators and the like is nearly non existant.我在十六进制、十进制、二进制、PHP 的按位运算符等方面的知识几乎不存在。 This function generates a valid v4 UUID up until one area.此函数生成一个有效的 v4 UUID,直到一个区域。 A v4 UUID should be in the form of: v4 UUID 应采用以下形式:

xxxxxxxx-xxxx- 4 xxx- y xxx-xxxxxxxxxxxx xxxxxxxx-xxxx- 4 xxx- y xxx-xxxxxxxxxxxx

where y is 8, 9, A, or B. This is where the functions fails as it doesn't adhere to that.其中y是 8、9、A 或 B。这是函数失败的地方,因为它不遵守那个。

I was hoping someone with more knowledge than me in this area could lend me a hand and help me fix this function so it does adhere to that rule.我希望在这方面比我有更多知识的人可以帮助我并帮助我修复此功能,因此它确实遵守该规则。

The function is as follows:功能如下:

<?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;
}

?>

Thanks to anyone that can help me out.感谢任何可以帮助我的人。


解决方案:

参考一: https://stackoom.com/question/8Yl6
参考二: PHP function to generate v4 UUID
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章