How to generate a new GUID?

前端 未结 6 1353
不知归路
不知归路 2020-11-29 02:15

I\'m working on a web service which requires a new GUID() passed as a reference to a method within the service.

I am not familiar with C#

6条回答
  •  悲哀的现实
    2020-11-29 02:48

    If you just need a very unique ID:

    $uid = dechex( microtime(true) * 1000 ) . bin2hex( random_bytes(8) );
    

    If ID's are generated more than 1 millisecond apart, they are 100% unique.

    If two ID's are generated at shorter intervals, this would generate ID's that are 99.999999999999999999% likely to be globally unique (collision in 1 of 10^18)

    You can increase this number by adding more digits, but to generate 100% unique ID's you will need to use a global counter.

    if you really do need RFC compliance, this will pass as a valid version 4 GUID:

    $guid = vsprintf('%s%s-%s-4000-8%.3s-%s%s%s0',str_split(dechex( microtime(true) * 1000 ) . bin2hex( random_bytes(8) ),4));
    

    This follows the intention, but not the letter of the RFC. Among other discrepancies it's a few random digits short. (Add more random digits if you need it) The upside is that this is fast, compared to 100% compliant code. You can test your GUID here

提交回复
热议问题