Created
July 23, 2013 13:12
-
-
Save openprojdev/6062247 to your computer and use it in GitHub Desktop.
generate UUID , RFC 4122, extracted from cakePHP String class. This snippet depends on $_SERVER var set by the web server, and hence would recommend pecl extension http://pecl.php.net/package/uuid if this function is to be called from the CLI Remember to change the SALT line 52
This file contains hidden or 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
| /** | |
| * Generate a random UUID | |
| * | |
| * @see http://www.ietf.org/rfc/rfc4122.txt | |
| * @return RFC 4122 UUID | |
| */ | |
| function uuid() { | |
| $node = $_SERVER['SERVER_ADDR']; | |
| if (strpos($node, ':') !== false) { | |
| if (substr_count($node, '::')) { | |
| $node = str_replace( | |
| '::', str_repeat(':0000', 8 - substr_count($node, ':')) . ':', $node | |
| ); | |
| } | |
| $node = explode(':', $node); | |
| $ipSix = ''; | |
| foreach ($node as $id) { | |
| $ipSix .= str_pad(base_convert($id, 16, 2), 16, 0, STR_PAD_LEFT); | |
| } | |
| $node = base_convert($ipSix, 2, 10); | |
| if (strlen($node) < 38) { | |
| $node = null; | |
| } else { | |
| $node = crc32($node); | |
| } | |
| } elseif (empty($node)) { | |
| $host = $_ENV['HOSTNAME']; | |
| if (empty($host)) { | |
| $host = $_ENV['HOST']; | |
| } | |
| if (!empty($host)) { | |
| $ip = gethostbyname($host); | |
| if ($ip === $host) { | |
| $node = crc32($host); | |
| } else { | |
| $node = ip2long($ip); | |
| } | |
| } | |
| } elseif ($node !== '127.0.0.1') { | |
| $node = ip2long($node); | |
| } else { | |
| $node = null; | |
| } | |
| if (empty($node)) { | |
| $node = crc32('YOUR SAULT GOES HERE #2n$$NL90)ujnjk'); | |
| } | |
| if (function_exists('hphp_get_thread_id')) { | |
| $pid = hphp_get_thread_id(); | |
| } elseif (function_exists('zend_thread_id')) { | |
| $pid = zend_thread_id(); | |
| } else { | |
| $pid = getmypid(); | |
| } | |
| if (!$pid || $pid > 65535) { | |
| $pid = mt_rand(0, 0xfff) | 0x4000; | |
| } | |
| list($timeMid, $timeLow) = explode(' ', microtime()); | |
| return sprintf( | |
| "%08x-%04x-%04x-%02x%02x-%04x%08x", (int)$timeLow, (int)substr($timeMid, 2) & 0xffff, | |
| mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3f) | 0x80, mt_rand(0, 0xff), $pid, $node | |
| ); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment