Create a short unique ID in PHP
Mads Kristensen describes a nice way of generating shorter UUIDs in C#. The idea is to take the 16 bytes of a UUID and convert them to a readable string via a Base64 encoder. The result is a string of 22 characters instead of 32, which is particularly convenient for web services since it makes the URLs 10 characters shorter.
I’ve implemented a version of it in PHP. Just copy and paste the code below and call createBase64UUID()
function createBase64UUID() { $uuid = com_create_guid(); $byteString = ""; // Remove the dashes from the string $uuid = str_replace("-", "", $uuid); // Remove the opening and closing brackets $uuid = substr($uuid, 1, strlen($uuid) - 2); // Read the UUID string byte by byte for($i = 0; $i < strlen($uuid); $i += 2) { // Get two hexadecimal characters $s = substr($uuid, $i, 2); // Convert them to a byte $d = hexdec($s); // Convert it to a single character $c = chr($d); // Append it to the byte string $byteString = $byteString.$c; } // Convert the byte string to a base64 string $b64uuid = base64_encode($byteString); // Replace the "/" and "+" since they are reserved characters $b64uuid = str_replace("/", "_", $b64uuid); $b64uuid = str_replace("+", "-", $b64uuid); // Remove the trailing "==" $b64uuid = substr($b64uuid, 0, strlen($b64uuid) - 2); return $b64uuid; }
February 15th, 2011 at 5:24
VERY nice little bit of code. Even 64 bit machines can’t do this natively and you came up with the exact way to do it. Eventually, I plan on finding out if Java does it simpler. I think it does 128 bit numbers natively.