Top

Generate a UUID Using PHP

Generate a standardized UUIDv4 compliant string using PHP.

Generate a UUID version 4 string using PHP

So, you need to generate a UUID for your PHP application; No problem! Although PHP has other unique id functions built in, sometimes you need a standard UUID format compliant to the specification. In those cases, here’s a little snippet for you:

<?php

/**
* Generate 128 bits of random data
* @see http://tools.ietf.org/html/rfc4122#section-4.4
* @return    string
*
*/

function guidv4() {
  $data     = openssl_random_pseudo_bytes( 16 );
  $data[6]  = chr( ord( $data[6] ) & 0x0f | 0x40 ); // set version to 0100
  $data[8]  = chr( ord( $data[8] ) & 0x3f | 0x80 ); // set bits 6-7 to 10
  return vsprintf( '%s%s-%s-%s-%s-%s%s%s', str_split( bin2hex( $data ), 4 ) );
}
?>

I sourced this originally from phppro.org, and it has came in handy over the years! Hope it helps you.

Think I might be a good fit for your project?

Let's get the conversation started!