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