note 119168 added to function.com-create-guid
| From: | (daveatpds-ukdotcom) | Date: | Thu, 14 Apr 2016 10:07:21 +0000 |
| Subject: | note 119168 added to function.com-create-guid | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-205230@lists.php.net to get a copy of this message | ||
Here's my final version of a GUIDv4 function (based on others work here) that should work on
all platforms and gracefully fallback to less cryptographically secure version if others are not
supported...
<?php
/**
* Returns a GUIDv4 string
*
* Uses the best cryptographically secure method
* for all supported pltforms with fallback to an older,
* less secure version.
*
* @param bool $trim
* @return string
*/
function GUIDv4 ($trim = true)
{
// Windows
if (function_exists('com_create_guid') === true) {
if ($trim === true)
return trim(com_create_guid(), '{}');
else
return com_create_guid();
}
// OSX/Linux
if (function_exists('openssl_random_pseudo_bytes') === true) {
$data = openssl_random_pseudo_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
// Fallback (PHP 4.2+)
mt_srand((double)microtime() * 10000);
$charid = strtolower(md5(uniqid(rand(), true)));
$hyphen = chr(45); // "-"
$lbrace = $trim ? "" : chr(123); // "{"
$rbrace = $trim ? "" : chr(125); // "}"
$guidv4 = $lbrace.
substr($charid, 0, 8).$hyphen.
substr($charid, 8, 4).$hyphen.
substr($charid, 12, 4).$hyphen.
substr($charid, 16, 4).$hyphen.
substr($charid, 20, 12).
$rbrace;
return $guidv4;
}
?>
----
Server IP: 72.52.91.14
Probable Submitter: 81.148.109.47
----
Manual Page -- http://php.net/manual/en/function.com-create-guid.php
Edit -- https://master.php.net/note/edit/119168
Del: integrated -- https://master.php.net/note/delete/119168/integrated
Del: useless -- https://master.php.net/note/delete/119168/useless
Del: bad code -- https://master.php.net/note/delete/119168/bad+code
Del: spam -- https://master.php.net/note/delete/119168/spam
Del: non-english -- https://master.php.net/note/delete/119168/non-english
Del: in docs -- https://master.php.net/note/delete/119168/in+docs
Del: other reasons-- https://master.php.net/note/delete/119168
Reject -- https://master.php.net/note/reject/119168
Search -- https://master.php.net/manage/user-notes.php