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 (inarray($generatedUUID, $generatedUUIDs)) { echo 'matching same uuid in run ' . $i . PHPEOL; exit(); } else { $generatedUUIDs[] = $generatedUUID; } if (inarray($generatedMd5, $generatedMd5s)) { echo 'matching same md5 in run ' . $i . PHPEOL; 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', mtrand(0, 0xffff), mtrand(0, 0xffff), mtrand(0, 0xffff), mtrand(0, 0x0fff) | 0x4000, mtrand(0, 0x3fff) | 0x8000, mtrand(0, 0xffff), mtrand(0, 0xffff), mtrand(0, 0xffff)); }

Translate to de es fr it pt ja

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

Add Comment

Standard emoticons like :-) and ;-) are converted to images.
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.
CAPTCHA

Markdown format allowed
Form options