0

I need a string with max 6 length and mixed of number and alphabet. I checked:

How can I make short random unique keys, like YouTube video IDs, in PHP?

and

PHP generate a unique string

that was very useful but they make string with length 10 - 12. my question is that output of this code is always unique or not?

base_convert(microtime(false), 6, 36);

or

base_convert(uniqid('test',true), 6, 36);

Note: I convert from base 6 but the input is obviously not going to be base 6. I do it because if convert from 10 to 36 it generate 10-12 length.

Community
  • 1
  • 1
  • I don't think this would work at all since you're trying to convert from base 6 but the input is obviously not going to be base 6 – apokryfos Feb 06 '17 at 15:58
  • @apokryfos yes I do. I do it because if I convert from 10 to 36 it generate 10-12 length. what can I do? – Mehrdad Dadkhah Feb 07 '17 at 05:42
  • But base 6 means that the numbers will all be between 0-5 which is not the case. You should instead do a [`substr`](http://php.net/manual/en/function.substr.php) – apokryfos Feb 07 '17 at 07:31
  • @apokryfos yes but I think if use substr it's not never unique – Mehrdad Dadkhah Feb 07 '17 at 08:11
  • Guaranteeing uniqueness is very expensive. Getting something that's unique in the vast majority of cases is what most people opt for. Even the algorithms to generate GUIDs (which are supposed to be globally unique identifiers) only generate unique ones with high probability. – apokryfos Feb 07 '17 at 08:15

1 Answers1

1

Short Answer: No, but if you are doing something tiny like a personal website, or a internal only tool used by very few people it will be OK.

Long answer: Definitely not if you are trying to do something secure, or using multiple servers that share database. Attackers can figure out exactly how long it takes for their request to reach your server and bombard it with their requests until your server generates duplicate IDs if you rely on microtime. uniqid function is not guaranteed to return uniq value(straight from php manual), and will definitely generate duplicate IDs if you are updating your time using NTP and it adjusts your time to 5 seconds ago.

Dimi
  • 1,255
  • 11
  • 20
  • how can I make it better? – Mehrdad Dadkhah Feb 07 '17 at 08:12
  • The easiest way to make something unique is to have atomic operations with counter. The easiest way to do it is with SQL database, and relying on their auto incremented ID, since they already took care of everything possible. If you do not want to use database, you can create a file on filesystem that will store a simple integer. You will need to implement exclusive file locking, lock waiting, and lock release. read about http://php.net/manual/en/function.flock.php – Dimi Feb 07 '17 at 13:53