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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章