How should I create my GUID?

梦想与她 提交于 2019-12-03 10:53:20

EDIT:

Yikes! I forgot about this ancient answer of mine. To clarify confusion created by my naivety (consistent with the comments made below): MD5 (like most useful hashes, by their nature) are not injective, so their output is not guaranteed to be unique for all inputs.

If hash collisions are an issue (in this case, they are), using this technique will require checking, after hashing, whether an identical key has already been generated.


Since uniqid uses the current time in microseconds to generate the guid, there is virtually no chance you'll ever run into the same one twice.

So if you're just using it to make unique filenames, uniqid() will be sufficient. If you want to prevent users from guessing the guid, you might as well make it harder and md5 it as well.

GUID is Microsoft's version of UUID. PHP's uniqid is version 4 of UUID. Definitely good enough.

I also want to create guid for calling .net api and this function generate a key in guid format and it works for me

function generateGuid($include_braces = false) {
    if (function_exists('com_create_guid')) {
        if ($include_braces === true) {
            return com_create_guid();
        } else {
            return substr(com_create_guid(), 1, 36);
        }
    } else {
        mt_srand((double) microtime() * 10000);
        $charid = strtoupper(md5(uniqid(rand(), true)));

        $guid = substr($charid,  0, 8) . '-' .
                substr($charid,  8, 4) . '-' .
                substr($charid, 12, 4) . '-' .
                substr($charid, 16, 4) . '-' .
                substr($charid, 20, 12);

        if ($include_braces) {
            $guid = '{' . $guid . '}';
        }

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