Will this following function always generate a unique string? What will be the length range of generated string from the following function? Can it be improved to generate more uniqueness?
base_c开发者_如何学运维onvert(mt_rand(10, 99) . intval(microtime(true) * 100), 8, 36);
Thanks
Keep in mind that it is generally a bad idea to write your own random/unique functions. Like KingCrunch mentioned PHP had a built-in function uniqid that does precisely what you want.
To answer your question:
The function will not always generate a unique string, it is impossible to do so. However good functions make it extremely unlikely (magnitudes of times smaller than winning the lottery) and thus unique enough in practice.
length:
- mt_rand(10,99) : generates a number in the range [10,99] (2 digits)
- intval(microtime(true)*100) will get the current unix timestamp plus 2 digits of the milliseconds. The timestamp is (at the moment) 10 digits long (and will remain so for about a century) so the total number of digits is 12 (decimal) digits
It then treats the number as a base_8 number this will fail often, as base_8 does not know the number 8 or 9. I do not know the exact PHP behaviour in this case but it is invalid nonetheless. If you act like the number is treated as base 10, you have the following scenario question: how much digits (base 36) are needed to represent numbers between 10^13 (if mt_rand generates 10) and 10^14 (if mt_rand generates 99).
The smallest number where base_36 needs 9 digits for is 2,821,109,907,457 which is lower than the underbound of your number. The largest number it can represent with 9 digits is however 101,559,956,668,416 (~10^14). Thus it will generate a 9-digit base_36 number.
[edit] I saw you specifically needed a 6-character unique string. Keep in mind that 6-characters is relatively short so uniqueness is hard to guarantee. Your best bet would still be
substr(uniqid(), 0, 6);
It will be better than any function you manage to come up on your own with.[/edit]
Simple use uniqid() good inbuilt function. This also generate unique id from timestamp. So No. will always be unique.
The answer to your question depends on your requirement. I use this function for a generic not-so-secure requirement. Only returns Alphabets and Numbers, clearing out "similar looking" characters: -
function fGetRandomString($vLength = 4) {
$sRandomString = ""; $sChr = "";
for ($i = 0 ; $i < $vLength ; $i++) {
$vState = rand(1, 3);
switch ($vState) {
case 1: $sChr = chr(rand(65, 90)); break; // CAPS (A-Z)
case 2: $sChr = chr(rand(97, 122)); break; // small (a-z)
case 3: $sChr = chr(rand(48, 57)); break; // Numbers (0-9)
}
if (!in_array($sChr, array('O', 'o', '0', '1', 'l'))) $sRandomString .= $sChr;
else $i--;
}
return $sRandomString;
}
Good Luck!
精彩评论