Skip to content

php - create uuid in php

If you need a kind of unique id creation inside php (but can not or do not want to use your database for this job), here is a small function for this. I have also implemented a md5 hash compare. You can replace your current md5 hash method with this one (if you are getting errors in your unittests for e.g. ;-) ).

?php $generatedUUIDs = array(); $generatedMd5s = array(); for($i = 0;$i<10000;$i++) { $generatedUUID = createUUID(); $generatedMd5 = md5($generatedUUID); if (in_array($generatedUUID, $generatedUUIDs)) { echo 'matching same uuid in run ' . $i . PHP_EOL; exit(); } else { $generatedUUIDs[] = $generatedUUID; } if (in_array($generatedMd5, $generatedMd5s)) { echo 'matching same md5 in run ' . $i . PHP_EOL; exit(); } else { $generatedMd5s[] = $generatedMd5; } } echo 'Run ' . $i . ' creations of UUIDs successfully.' . PHP_EOL; function createUUID() { return 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)); }


No Trackbacks


Display comments as Linear | Threaded

No comments

Add Comment

E-Mail addresses will not be displayed and will only be used for E-Mail notifications.
To leave a comment you must approve it via e-mail, which will be sent to your address after submission.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.

Markdown format allowed
Form options