PHP verify valid UUID

11,040

Solution 1

According to Wikipedia the format of UUID v4 is:

Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B. e.g. f47ac10b-58cc-4372-a567-0e02b2c3d479.

The corresponding regex is:

/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i

Solution 2

I use regex validation along with string validation to check if the given string is in valid UUID format.

if (!is_string($uuid) || (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $uuid) !== 1)) {
    return false;
}

You can see the full gist here.

Share:
11,040
Peter
Author by

Peter

Updated on June 04, 2022

Comments

  • Peter
    Peter almost 2 years

    I found the following Javascript function in another answer:

    function createUUID() {
        var s = [];
        var hexDigits = "0123456789abcdef";
    
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
    
        s[14] = "4";
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
        s[8] = s[13] = s[18] = s[23] = "-";
    
        var uuid = s.join("");
        return uuid;
    }
    

    This creates an RFC valid UUID/GUID in javascript.. What I want to know is if there is a way to validate the string once it arrives to the PHP side. I found a regex that would potentially validate everything roughly that format as true:

    /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/

    but using that as long as you specified a string of equal length and format it would pass validation.

    Is there any way to add some sort of seed to the javascript function and then verify that in the PHP or if there was a way for PHP to validate the number that was passed matches with the correct format or something?

    Any help is greatly appreciated.