diff --git a/app/common.php b/app/common.php index 757f4b3..8f7f5b5 100644 --- a/app/common.php +++ b/app/common.php @@ -135,4 +135,38 @@ function throwError(string $message, ?int $status = null, array $data = []) { is_null($status) && $status = config('status.error'); throw new BaseException(['status' => $status, 'message' => $message, 'data' => $data]); +} + +/** + * 获取全局唯一标识符 + * @param bool $trim + * @return string + */ +function get_guid_v4(bool $trim = true): string +{ + // Windows + if (function_exists('com_create_guid') === true) { + $charid = com_create_guid(); + return $trim ? trim($charid, '{}') : $charid; + } + // 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(intval((double)microtime() * 10000)); + $charid = strtolower(md5(uniqid((string)rand(), true))); + $hyphen = chr(45); // "-" + $lbrace = $trim ? "" : chr(123); // "{" + $rbrace = $trim ? "" : chr(125); // "}" + return $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; } \ No newline at end of file