0

I am using the following function, it uses mt_rand but there is chance, I believe, that it could generate a duplicate. Is there a better way to do this?

 sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
CJD
  • 782
  • 3
  • 10
  • 20
  • Possible duplicate of [PHP function to generate v4 UUID](http://stackoverflow.com/questions/2040240/php-function-to-generate-v4-uuid) – Alessandro Da Rugna Nov 14 '15 at 15:23
  • That question does not answer my problem. I am specifically looking for advice on creating non-duplicates. It doesn't have to be random, just unique. – CJD Nov 14 '15 at 15:45
  • I see where you're coming from, the problem is 'slim' = 'possible', even if its insanely unlikely. I think I might just have to perform a duplicate check through the database. – CJD Nov 14 '15 at 20:41
  • your code DOES NOT generate an UUID4 - it doesn't have the **4** in the required position. If you want a non-duplicate could you just auto increment it at every function call? – Alessandro Da Rugna Nov 15 '15 at 10:33

1 Answers1

4

If you want to create real UUID v4 in PHP then the best thing to do is use this package - https://github.com/ramsey/uuid - that has been thoroughly tested and is used by many other packages.

EspadaV8
  • 658
  • 5
  • 12