UUID – Pogopixels’ Blog http://pogopixels.com/blog Just another WordPress weblog Thu, 17 Mar 2016 13:29:10 +0000 en-US hourly 1 https://wordpress.org/?v=4.7.9 Create a short unique ID in PHP http://pogopixels.com/blog/creating-a-short-unique-id-in-php/ http://pogopixels.com/blog/creating-a-short-unique-id-in-php/#comments Tue, 21 Oct 2008 18:01:55 +0000 http://pogopixels.com/blog/?p=21 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;
}
]]>
http://pogopixels.com/blog/creating-a-short-unique-id-in-php/feed/ 1