How to Create UUID in PHP?


The UUID, Universally unique identifier, is said to be large enough to cover every inch of the land on earth. It can be generated at any computer without the central database and at the same time it can be used to get the uniqueness and randomness.

There are currently 5 versions of UUID and the fourth version is totally random, which is easier to generate. On Windows PHP, there is a function com_create_guid however at Linux, there is not.

Therefore, the following can be inserted into your PHP core function library to ensure that the com_create_guid works at any platform.

1
2
3
4
5
6
7
8
9
10
11
if (!function_exists('com_create_guid')) {
  function com_create_guid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
        mt_rand( 0, 0xffff ),
        mt_rand( 0, 0x0fff ) | 0x4000,
        mt_rand( 0, 0x3fff ) | 0x8000,
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
  }
}
if (!function_exists('com_create_guid')) {
  function com_create_guid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
        mt_rand( 0, 0xffff ),
        mt_rand( 0, 0x0fff ) | 0x4000,
        mt_rand( 0, 0x3fff ) | 0x8000,
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
  }
}

References

1. http://leonax.net/p/6970/generate-uuid-in-php/

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
225 words
Last Post: Simple HTA Template to Run Utility on File
Next Post: How to Get Host Root Domain URL in PHP?

The Permanent URL is: How to Create UUID in PHP?

Leave a Reply