Generate UUID in PHP

Table of Contents

UUID Version 1 using MAC address and timestamp

    <?php
      function generateUuidV1() {
        $node = getNodeIdentifier(); // Get MAC address
        $timeLow = microtime(true) * 10000 & 0xFFFFFFF; // Get lower 32 bits of current timestamp
        $timeMid = microtime(true) * 10000 >> 4 & 0xFFFF; // Get middle 16 bits of current timestamp
        $timeHiAndVersion = microtime(true) * 10000 >> 12 | 1 << 12; // Get higher 16 bits of current timestamp with version number 1

        return sprintf(
          '%08x-%04x-%04x-%04x-%012x',
          $timeLow,
          $timeMid,
          $timeHiAndVersion,
          $node,
          random_int(pow(16, 12), pow(16, 13) - 1) // Generate random 48-bit number
        );
      }

      function getNodeIdentifier() {
        $file = '/sys/class/net/eth0/address';
        $macAddress = '';

        if (file_exists($file)) {
          $macAddress = file_get_contents($file);
        } else {
          $networkInterfaces = network_interfaces();

          foreach ($networkInterfaces as $networkInterface) {
            if ($networkInterface['flags'] & IFF_BROADCAST) {
              $macAddress = $networkInterface['mac'];
              break;
            }
          }
        }

        return hexdec(str_replace(':', '', $macAddress)) & 0xFFFFFFFFFFFF;
      }
    ?>
  

UUID Version 3 using MD5 hashing

    <?php
      function generateUuidV3($namespace, $name) {
        $hash = md5($namespace . $name);
        $uuid = substr($hash, 0, 8) . '-' .
                substr($hash, 8, 4) . '-' .
                substr($hash, 12, 4) . '-' .
                substr($hash, 16, 4) . '-' .
                substr($hash, 20, 12);

        return $uuid;
      }
    ?>
  

UUID Version 4 using random data

    <?php
      function generateUuidV4() {
        $data = random_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Set version
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // Set variant

        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
      }
    ?>
  

UUID Version 5 using SHA-1 hashing

    <?php
      function generateUuidV5($namespace, $name) {
        $hash = sha1($namespace . $name);
        $uuid = substr($hash, 0, 8) . '-' .
                substr($hash, 8, 4) . '-' .
                substr($hash, 12, 4) . '-' .
                substr($hash, 16, 4) . '-' .
                substr($hash, 20, 12);

        return $uuid;
      }
    ?>
  

Summary

In this tutorial, we explored different ways of generating UUIDs in php. We covered the following methods:

  1. UUID Version 1 using MAC address and timestamp
  2. UUID Version 3 using MD5 hashing
  3. UUID Version 4 using random data
  4. UUID Version 5 using SHA-1 hashing

Each method has its own characteristics and use cases. By using these methods, you can generate unique identifiers for various purposes in your php applications.

References