PHP函数生成v4 UUID
因此,我一直在做一些挖掘工作,并试图拼凑一个在PHP中生成有效v4
UUID的函数。这是我能找到的最接近的。我对十六进制,十进制,二进制,PHP的按位运算符之类的知识几乎不存在。该功能会生成一个有效的v4
UUID,直到一个区域。v4 UUID的形式应为:
xxxxxxxx-xxxx- xxx- xxx-xxxxxxxxxxxx
其中 是8、9,A或B。这是函数失败的原因,因为它不遵守。
我希望在这个领域比我有更多知识的人可以帮助我并帮助我修复此功能,以便它确实遵守该规则。
功能如下:
<?phpfunction 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;
}
?>
感谢任何可以帮助我的人。
回答:
从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 )
);
}
以上是 PHP函数生成v4 UUID 的全部内容, 来源链接: utcz.com/qa/425408.html