Jacob Boddey
Jacob Boddey

Reputation: 51

Obtain UUID from MongoDB in PHP

I have a Binary UUID in MongoDB that was saved to MongoDB using Java. It looks like this in string format:

9adc22fe-b775-4913-aee8-3d529ad74d5e

When saved to MongoDB it appears like this:

Binary('k0HT91W0Q/mU02IsyeFttg==')

I have used the MongoDB PHP driver to get it from the collection, giving this:

object(MongoDB\BSON\Binary)#22 (2) { ["data"]=> string(16) "Iu��"ܚ]LלR=�" ["type"]=> int(3) }

I know I can extract the data using $var->getData(), but I am missing the final process to get it back to the string format above. I have tried using base64_decode, bin2hex and a few other methods, but they are returning incorrect values.

How do you obtain the string value of a UUID stored in MongoDB?

Any help would be greatly appreciated, Thanks

Upvotes: 1

Views: 1071

Answers (1)

Jacob Boddey
Jacob Boddey

Reputation: 51

I have managed to solve this myself by using the toJUUID method from uuidhelpers.js, writing it in PHP as follows:

$hex = bin2hex($uuid->getData());
$msb = substr($hex, 0, 16);
$lsb = substr($hex, 16, 16);
$msb = substr($msb, 14, 2) . substr($msb, 12, 2) . substr($msb, 10, 2) . substr($msb, 8, 2) . substr($msb, 6, 2) . substr($msb, 4, 2) . substr($msb, 2, 2) . substr($msb, 0, 2);
$lsb = substr($lsb, 14, 2) . substr($lsb, 12, 2) . substr($lsb, 10, 2) . substr($lsb, 8, 2) . substr($lsb, 6, 2) . substr($lsb, 4, 2) . substr($lsb, 2, 2) . substr($lsb, 0, 2);
$hex = $msb . $lsb;
$uuid = substr($hex, 0, 8) . '-' . substr($hex, 8, 4) . '-' . substr($hex, 12, 4) . '-' . substr($hex, 16, 4) . '-' . substr($hex, 20, 12);

I then wanted to convert the Java UUID back into BSON Binary format (type 3), I did this also using uuidhelpers.js, using the JUUID method, which looks like the following in PHP:

$hex = str_replace("-", "", $uuid);

$msb = substr($hex, 0, 16);
$lsb = substr($hex, 16, 16);
$msb = substr($msb, 14, 2) . substr($msb, 12, 2) . substr($msb, 10, 2) . substr($msb, 8, 2) . substr($msb, 6, 2) . substr($msb, 4, 2) . substr($msb, 2, 2) . substr($msb, 0, 2);
$lsb = substr($lsb, 14, 2) . substr($lsb, 12, 2) . substr($lsb, 10, 2) . substr($lsb, 8, 2) . substr($lsb, 6, 2) . substr($lsb, 4, 2) . substr($lsb, 2, 2) . substr($lsb, 0, 2);
$hex = $msb . $lsb;

$uuid = hex2bin($hex);
$uuid = new MongoDB\BSON\Binary($uuid, 3);

Upvotes: 4

Related Questions