PHP: AD ObjectGUID

As always you seem to spend a lot of time trying to find a function that does something.

This was one of those times.

The below code is what I came up with... and it works.

The best way to get the object guid is to use the following function:

    // This function will convert a binary value guid into a valid string.
    function bin_to_str_guid($object_guid) {
        $hex_guid = bin2hex(base64_decode($object_guid));
        $hex_guid_to_guid_str = '';
        for($k = 1; $k <= 4; ++$k) {
            $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
        }
        $hex_guid_to_guid_str .= '-';
        for($k = 1; $k <= 2; ++$k) {
            $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
        }
        $hex_guid_to_guid_str .= '-';
        for($k = 1; $k <= 2; ++$k) {
            $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
        }
        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
        return strtoupper($hex_guid_to_guid_str);
    }

$object_guid = $result[0]["objectguid"][0];
echo bin_to_str_guid($object_guid)."<br>";

You can then validate that the GUID has been converted correctly by checking its length.. which should be 16bits.

echo mb_strlen($object_guid, '8bit');

Using the above code the object guid is formatted like so:

1A9C457E-00C5-4B2C-8C4D-4A6B7F81AC4B

Which matches how it is seen in AD.