Possible Duplicate:
PHP: How to generate a random, unique, alphanumeric string?
Does this formula produce collision ?
substr(md5(uniqid(rand()))),0,6)
How to generate a unique ID with only numbers (i.e 7 digits) ?
Possible Duplicate:
PHP: How to generate a random, unique, alphanumeric string?
Does this formula produce collision ?
substr(md5(uniqid(rand()))),0,6)
How to generate a unique ID with only numbers (i.e 7 digits) ?
uniqid generates a 13 char string, how to reduce it to 7 char or 7 digits without risk of collision ?
As long as you mean collision while transposing output of uniqid
into a new representation, you can do it like the following:
uniqid
returns a 13 character string, each character can be 0-9
or a-f
, so basically a hexadecimal number with one place, 0-15 decimal.Example:
$unique = uniqid(); # 13 characters
$sevenPairs = array_map('hexdec', str_split($unique, 2));
printf("Unique ID: %s\nSeven Pairs (digits): %s\n"
, $unique, implode(', ', $sevenPairs));
Output:
Unique ID: 4f8ace1eb736a
Seven Pairs (digits): 79, 138, 206, 30, 183, 54, 10
Take care that if you make use of the prefix part (in your question you use rand
), the length of the returned string by uniqid
can be larger than 13.
The easiest way is to get it from a database or text file, starting from 0 and incrementing it with 1 for each ID.
$id = strint(file_get_contents('counter.txt'));
file_put_content('counter.txt',++$id);
when using rand() there will be a bigger chance that you will get the same number. if you dont want an incremental value, use rand and check if the number is already used with a database.