Skip to content

Instantly share code, notes, and snippets.

@shanezhiu
Last active Jan 20, 2019
Embed
What would you like to do?
生成UUIDS
<?php
// 第一种方法
function UUIDS()
{
if (function_exists('com_create_guid'))
{
$uuid = com_create_guid();
return substr($uuid, 1, -1);
}
else
{
// php4.2开始,不需要给随机数种种子,由系统自动完成。
mt_srand((double)microtime() * 10000);
$charid = strtoupper(md5(uniqid(mt_rand(), true)));
$hyphen = chr(45);
$uuid = substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12);
return $uuid;
}
}
// 第二种生成uuid方法
// $uuidBin 需为16位十六进制数,可以使用md5(string,true)进行操作,md5带true操作,返回的是长为16位的二进制数。
public static function bin2uuid($uuidBin)
{
$hexArray = unpack('H*', $uuidBin);
$hex = strtoupper(array_shift($hexArray));
$components = [
substr($hex, 0, 8),
substr($hex, 8, 4),
substr($hex, 12, 4),
substr($hex, 16, 4),
substr($hex, 20, 12),
];
return implode('-', $components);
}
public static function uuid2bin($uuid)
{
// normalize to uppercase, remove hyphens
$hex = str_replace('-', '', strtolower($uuid));
// H for big-endian to behave similarly to MySQL's
// HEX() and UNHEX() functions.
$bin = pack('H*', $hex);
return $bin;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment