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($uuid1strlen($uuid) - 2); 

  // Read the UUID string byte by byte
  for($i 0$i strlen($uuid); $i += 2) {
    // Get two hexadecimal characters
    $s substr($uuid$i2);
    // 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($b64uuid0strlen($b64uuid) - 2); 

  return $b64uuid;
}

Tags: ,

One Response to “Create a short unique ID in PHP”

  1. Dennis Gearon Says:

    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.

Copyright © Pogopixels Ltd, 2008-2018