Posts Tagged ‘UUID’

Create a short unique ID in PHP

Tuesday, October 21st, 2008

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;
}
Copyright © Pogopixels Ltd, 2008-2018