PHP verify valid UUID

匆匆过客 提交于 2019-12-19 10:22:44

问题


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.


回答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



回答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.



来源:https://stackoverflow.com/questions/12808597/php-verify-valid-uuid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!