Last active
March 2, 2019 03:26
-
-
Save fdcore/15bdccf22c18e760f7a7 to your computer and use it in GitHub Desktop.
Encode long UUID to short binary string like youtube hash
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 | |
// echo uuid_encode('cd76b808-4017-4965-b9b1-2dbcf857e405'); | |
function uuid_encode($uuid){ | |
$binary = pack("h*", str_replace('-', '', $uuid)); | |
$binary = base64_encode($binary); | |
$binary = str_replace('/', '_', $binary); | |
$binary = str_replace('=', '', $binary); | |
return $binary; | |
} | |
// echo uuid_decode('3GeLgARxlFabG9LLj3VOUA'); | |
function uuid_decode($encoded){ | |
$encoded = str_replace('_', '/', $encoded).'=='; | |
$encoded = base64_decode($encoded); | |
$arr = unpack("h*", $encoded); | |
$string = preg_replace("/([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})/", "$1-$2-$3-$4-$5", $arr[1]); | |
return $string; | |
} | |
// http://www.php.net/manual/en/function.uniqid.php#94959 | |
function gen_uuid() { | |
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', | |
// 32 bits for "time_low" | |
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), | |
// 16 bits for "time_mid" | |
mt_rand( 0, 0xffff ), | |
// 16 bits for "time_hi_and_version", | |
// four most significant bits holds version number 4 | |
mt_rand( 0, 0x0fff ) | 0x4000, | |
// 16 bits, 8 bits for "clk_seq_hi_res", | |
// 8 bits for "clk_seq_low", | |
// two most significant bits holds zero and one for variant DCE1.1 | |
mt_rand( 0, 0x3fff ) | 0x8000, | |
// 48 bits for "node" | |
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment