<p>I looking for a way, specifically in PHP that I will be guaranteed to always get a unique key.</p>

<p>I have done the following:</p>

<pre><code>strtolower(substr(crypt(time()), 0, 7));
</code></pre>

<p>But I have found that once in a while I end up with a duplicate key (rarely, but often enough).</p>

<p>I have also thought of doing:</p>

<pre><code>strtolower(substr(crypt(uniqid(rand(), true)), 0, 7));
</code></pre>

<p>But according to the PHP website, uniqid() could, if uniqid() is called twice in the same microsecond, it could generate the same key. I'm thinking that the addition of rand() that it rarely would, but still possible.</p>

<p>After the lines mentioned above I am also remove characters such as L and O so it's less confusing for the user. This maybe part of the cause for the duplicates, but still necessary.</p>

<p>One option I have a thought of is creating a website that will generate the key, storing it in a database, ensuring it's completely unique.</p>

<p>Any other thoughts? Are there any websites out there that already do this that have some kind of API or just return the key. I found <a href="http://userident.com" rel="noreferrer">http://userident.com</a> but I'm not sure if the keys will be completely unique.</p>

<p>This needs to run in the background without any user input.</p>

[{'answer_id': 55224, 'author': 'Humpton', 'author_id': 1444, 'author_profile': 'https://Stackoverflow.com/users/1444', 'pm_score': 0, 'selected': False, 'text': '<p>Without writing the code, my logic would be:</p>\n\n<p>Generate a random string from whatever acceptable characters you like.<br>\nThen add half the date stamp (partial seconds and all) to the front and the other half to the end (or somewhere in the middle if you prefer).</p>\n\n<p>Stay JOLLY!<br>\nH</p>\n'}, {'answer_id': 55226, 'author': 'Espo', 'author_id': 2257, 'author_profile': 'https://Stackoverflow.com/users/2257', 'pm_score': 0, 'selected': False, 'text': '<p>If you use your original method, but add the username or emailaddress in front of the password, it will always be unique if each user only can have 1 password.</p>\n'}, {'answer_id': 55227, 'author': 'Frank Krueger', 'author_id': 338, 'author_profile': 'https://Stackoverflow.com/users/338', 'pm_score': 0, 'selected': False, 'text': '<p>You may be interested in this article which deals with the same issue: <a href="http://blogs.msdn.com/oldnewthing/archive/2008/06/27/8659071.aspx" rel="nofollow noreferrer">GUIDs are globally unique, but substrings of GUIDs aren\'t</a>.</p>\n\n<blockquote>\n  <blockquote>\n    <p>The goal of this algorithm is to use the combination of time and location ("space-time coordinates" for the relativity geeks out there) as the uniqueness key. However, timekeeping is not perfect, so there\'s a possibility that, for example, two GUIDs are generated in rapid succession from the same machine, so close to each other in time that the timestamp would be the same. That\'s where the uniquifier comes in.</p>\n  </blockquote>\n</blockquote>\n'}, {'answer_id': 55233, 'author': 'Mark Biek', 'author_id': 305, 'author_profile': 'https://Stackoverflow.com/users/305', 'pm_score': 0, 'selected': False, 'text': "<p>I usually do it like this:</p>\n\n<pre><code>$this-&gt;password = '';\n\nfor($i=0; $i&lt;10; $i++)\n{\n    if($i%2 == 0)\n        $this-&gt;password .= chr(rand(65,90));\n    if($i%3 == 0)\n        $this-&gt;password .= chr(rand(97,122));\n    if($i%4 == 0)\n        $this-&gt;password .= chr(rand(48,57));\n}\n</code></pre>\n\n<p>I suppose there are some theoretical holes but I've never had an issue with duplication.  I usually use it for temporary passwords (like after a password reset) and it works well enough for that.</p>\n"}, {'answer_id': 55241, 'author': 'Adam Lerman', 'author_id': 673, 'author_profile': 'https://Stackoverflow.com/users/673', 'pm_score': -1, 'selected': False, 'text': '<p>I usually do a random substring (randomize how many chars between 8 an 32, or less for user convenience) or the MD5 of some value I have gotten in, or the time, or some combination. For more randomness I do MD5 of come value (say last name) concatenate that with the time, MD5 it again, then take the random substring. Yes, you <em>could</em> get equal passwords, but its not very likely at all.</p>\n'}, {'answer_id': 55245, 'author': 'dF.', 'author_id': 3002, 'author_profile': 'https://Stackoverflow.com/users/3002', 'pm_score': 0, 'selected': False, 'text': '<p>You might be interested in Steve Gibson\'s over-the-top-secure implementation of a password generator (no source, but he has a detailed description of how it works) at <a href="https://www.grc.com/passwords.htm" rel="nofollow noreferrer">https://www.grc.com/passwords.htm</a>.</p>\n<p>The site creates huge 64-character passwords but, since they\'re completely random, you could easily take the first 8 (or however many) characters for a less secure but &quot;as random as possible&quot; password.</p>\n<p>EDIT: from your later answers I see you need something more like a GUID than a password, so this probably isn\'t what you want...</p>\n'}, {'answer_id': 55247, 'author': 'Jason Cohen', 'author_id': 4926, 'author_profile': 'https://Stackoverflow.com/users/4926', 'pm_score': 1, 'selected': False, 'text': '<p><strong>Any algorithm will result in duplicates</strong>.</p>\n\n<p>Therefore, might I suggest that you use your existing algorithm* and simply check for duplicates?</p>\n\n<p>*Slight addition: If <code>uniqid()</code> can be non-unique based on time, also include a global counter that you increment after every invocation.  That way something is different even in the same microsecond.</p>\n'}, {'answer_id': 55249, 'author': 'George Mauer', 'author_id': 5056, 'author_profile': 'https://Stackoverflow.com/users/5056', 'pm_score': 0, 'selected': False, 'text': '<p>As Frank Kreuger commented, go with a GUID generator.</p>\n\n<p>Like <a href="http://www.phpclasses.org/browse/package/1738.html" rel="nofollow noreferrer">this one</a></p>\n'}, {'answer_id': 55298, 'author': 'zigdon', 'author_id': 4913, 'author_profile': 'https://Stackoverflow.com/users/4913', 'pm_score': 0, 'selected': False, 'text': "<p>I'm still not seeing why the passwords have to be unique?  What's the downside if 2 of your users have the same password?</p>\n\n<p>This is assuming we're talking about passwords that are tied to userids, and not just unique identifiers.  If <em>that's</em> what you're looking for, why not use GUIDs?</p>\n"}, {'answer_id': 55324, 'author': 'Jim McKeeth', 'author_id': 255, 'author_profile': 'https://Stackoverflow.com/users/255', 'pm_score': 5, 'selected': True, 'text': '<p>There are only 3 ways to generate unique values, rather they be passwords, user IDs, etc.:</p>\n\n<ol>\n<li>Use an effective GUID generator - these are long and cannot be shrunk. If you only use part <strong>you FAIL</strong>.  </li>\n<li>At least part of the number is sequentially generated off of a single sequence.  You can add fluff or encoding to make it look less sequential.  Advantage is they start short - disadvantage is they require a single source.  The work around for the single source limitation is to have numbered sources, so you include the [source #] + [seq #] and then each source can generate its own sequence.  </li>\n<li>Generate them via some other means and then check them against the single history of previously generated values.</li>\n</ol>\n\n<p>Any other method is not guaranteed.  Keep in mind, fundamentally you are generating a binary number (it is a computer), but then you can encode it in Hexadecimal, Decimal, Base64, or a word list.  Pick an encoding that fits your usage.  Usually for user entered data you want some variation of Base32 (which you hinted at).</p>\n\n<p><strong>Note about GUIDS</strong>: They gain their strength of uniqueness from their length and the method used to generate them.  <em>Anything less than 128-bits is not secure.</em>  Beyond random number generation there are characteristics that go into a GUID to make it more unique.  Keep in mind they are only practically unique, not completely unique.  It is possible, although practically impossible to have a duplicate. </p>\n\n<p><strong>Updated Note about GUIDS</strong>: Since writing this I learned that many GUID generators use a cryptographically secure random number generator (difficult or impossible to predict the next number generated, and a not likely to repeat). There are actually 5 different <a href="http://en.wikipedia.org/wiki/Universally_Unique_Identifier#Definition" rel="noreferrer">UUID algorithms</a>. Algorithm 4 is what Microsoft currently uses for the Windows GUID generation API. A <a href="http://en.wikipedia.org/wiki/Globally_unique_identifier" rel="noreferrer">GUID</a> is Microsoft\'s implementation of the UUID standard.</p>\n\n<p><strong>Update</strong>: If you want 7 to 16 characters then you need to use either method 2 or 3.</p>\n\n<p><strong>Bottom line</strong>: Frankly there is no such thing as completely unique.  Even if you went with a sequential generator you would eventually run out of storage using all the atoms in the universe, thus looping back on yourself and repeating. Your only hope would be the heat death of the universe before reaching that point.</p>\n\n<p>Even the best random number generator has a possibility of repeating equal to the total size of the random number you are generating.  Take a quarter for example.  It is a completely random bit generator, and its odds of repeating are 1 in 2.  </p>\n\n<p>So it all comes down to your threshold of uniqueness.  You can have 100% uniqueness in 8 digits for 1,099,511,627,776 numbers by using a sequence and then base32 encoding it.  Any other method that does not involve checking against a list of past numbers only has odds equal to n/1,099,511,627,776 (where n=number of previous numbers generated) of not being unique.</p>\n'}, {'answer_id': 57672, 'author': 'Laith', 'author_id': 5961, 'author_profile': 'https://Stackoverflow.com/users/5961', 'pm_score': 0, 'selected': False, 'text': '<p>I do believe that part of your issue is that you are trying to us a singular function for two separate uses... passwords and transaction_id </p>\n\n<p>these really are two different problem areas and it really is not best to try to address them together.</p>\n'}, {'answer_id': 1426722, 'author': 'Vince', 'author_id': 173661, 'author_profile': 'https://Stackoverflow.com/users/173661', 'pm_score': 0, 'selected': False, 'text': "<p>I recently wanted a quick and simple random unique key so I did the following: </p>\n\n<pre><code>$ukey = dechex(time()) . crypt( time() . md5(microtime() + mt_rand(0, 100000)) ); \n</code></pre>\n\n<p>So, basically, I get the unix time in seconds and add a random md5 string generated from time + random number. It's not the best, but for low frequency requests it is pretty good. It's fast and works. </p>\n\n<p>I did a test where I'd generate thousands of keys and then look for repeats, and having about 800 keys per second there were no repetitions, so not bad. I guess it totally depends on mt_rand()</p>\n\n<p>I use it for a survey tracker where we get a submission rate of about 1000 surveys per minute... so for now (crosses fingers) there are no duplicates. Of course, the rate is not constant (we get the submissions at certain times of the day) so this is not fail proof nor the best solution... the tip is using an incremental value as part of the key (in my case, I used time(), but could be better). </p>\n"}, {'answer_id': 2472907, 'author': 'Marco Demaio', 'author_id': 260080, 'author_profile': 'https://Stackoverflow.com/users/260080', 'pm_score': 0, 'selected': False, 'text': "<p>Ingoring the crypting part that does not have much to do with creating a unique value I usually use this one:</p>\n\n<pre><code>function GetUniqueValue()\n{\n   static $counter = 0; //initalized only 1st time function is called\n   return strtr(microtime(), array('.' =&gt; '', ' ' =&gt; '')) . $counter++;\n}\n</code></pre>\n\n<p>When called in same process $counter is increased so value is always unique in same process.</p>\n\n<p>When called in different processes you must be really unlucky to get 2 microtime() call with the same values, think that microtime() calls usually have different values also when called in same script.</p>\n"}]
['https://Stackoverflow.com/questions/55218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5441/']