Last active
January 20, 2019 05:48
-
-
Save shanezhiu/14f461efb9edc89fb62697468424198c to your computer and use it in GitHub Desktop.
生成UUIDS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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