-3

I am working on my first real project ever, and I am a bit worried. I am trying to create a unique user id (I am using PHP and mysql). I did some research about this topic, and to be honest with you I was overwhelmed. The last thing I read was about something called uniqid(), but the article says [This function does not guarantee uniqueness of return value. Since most systems adjust system clock by NTP or like, system time is changed constantly... Source PHP manual]. Then I thought about adding a random prefix, and I came with this code below. Is enough for a unique user id ?

<?php

$sub = substr(str_shuffle('AQWZSXEDCRFVTGBYHNUJIKOLMP'),16); // returns the last 10 chars
$shuff = str_shuffle(strval(rand(1000,9999)).$sub); // shuffle the 10 random chars with 4 random number
$user_id = uniqid($shuff);

Ayb009
  • 220
  • 2
  • 11
  • 3
    my vote is for the mysql primary key – Book Of Zeus Jun 30 '21 at 14:41
  • 1
    Use a id column with AutoIncrement that will always be unique, to that table at least – RiggsFolly Jun 30 '21 at 14:42
  • 1
    `uniqid()` does not guarantee uniqueness, but it's notably bad if you omit its `$more_entropy` second argument. I've never worked in a project where the value was not generated by the DB engine but, if you go for the PHP route, you can find a reputable UUID library... or use sequential numbers: 1, 2, 3... :) – Álvaro González Jun 30 '21 at 14:44
  • Does this answers your question? [How to generate a random, unique, alphanumeric string?](https://stackoverflow.com/questions/1846202/how-to-generate-a-random-unique-alphanumeric-string) – 0stone0 Jun 30 '21 at 14:45
  • If you just want to generate a random alphanumeric string, look into [random_bytes()](https://www.php.net/manual/en/function.random-bytes.php). If the length is long enough (like 32+), it's highly improbable (not claiming impossible though) that you'll generate duplicates, but if you need 100% unique user id's, then you should do as others suggested, use an autoincremented primary key in your DB instead. – M. Eriksson Jun 30 '21 at 15:09

2 Answers2

1

For complete and guaranteed uniqueness, I would suggest using AutoIncrement as suggested above. Anything "random" generated via code isn't truly random, thus you are not guaranteed a unique identifier.

russell
  • 61
  • 6
1

No, there is never a 100% guarantee of uniqueness. Thats correct.

But the question you should ask should not be "is it unique?", but you should rather ask "is it unique enough?".

For having a unique id in a table, grab the highest number that can be found + 1. Normally the db system is doing that for you using auto incrementing the id. Thats unique enough in the context of this table but might not be unique enough for acting with other data sources.

If you want to be unique over several locations, prefix it with the id of the location etc.

Honestly, I Didn't faced any situations were it wasn't enough uniqueness.

Jim Panse
  • 2,220
  • 12
  • 34