How does php generate non-repeated card numbers like phone cards? they are all numbers and cannot contain letters. The first thought was: N-bit random number + auto-incrementing id of a table in the database + N-bit random number, instead of using the database. the only criterion is time. Use the timestamp to catch up with several random numbers. In this case, the 16 card number is generated: the timestamp is 10 digits + 6 digits, and the random number is 1316651745695261 & nbsp; how can php generate non-repeated card numbers?
Like a phone card, it's all numbers and cannot contain letters.
First thought:
N-bit random number + auto-increment id of a database table + N-bit random number
If you don't want to use a database, the only criterion is time. Use the timestamp to catch up with several random numbers.
Assume that the card number of 16 is generated as follows:
Timestamp: 10-digit + 6-digit random number: 1316651745695261
Sometimes multiple card numbers need to be generated in one loop. the timestamp in the previous cycle (basically the same, unless there are other time-consuming operations in the loop), the next six random numbers cannot be unique. Combined with microtime
Microtime is called cyclically for ten times:
0.80717200 1316675664
0.80720600 1316675664
0.80721300 1316675664
0.80721900 1316675664
0.80722400 1316675664
0.80723000 1316675664
0.80723600 1316675664
0.80724100 1316675664
0.80724600 1316675664
0.80725200 1316675664
I thought it would be easier to separate the numbers above 807172. Code:
PHP code
for($i=0;$i<10;$i++){ //echo $this->microtime_float(); echo $time = microtime(); $arr = explode(" ",$time); $micro = $arr[0]*100000000; $micro_str = substr($micro."",0,6); $timestamp = $arr[1]; echo "\t".$timestamp."".$micro_str; echo '
'; }
For the time being, there will be no repeated tests in the local windows environment. Will there be a more powerful server with high computing power and repeated microseconds?
In addition, the card numbers generated in this way are not easy to see at a glance. You cannot randomly intercept several of them for fear of losing the uniqueness. I don't know if there is a good method.
For example, how does one generate a mobile recharge card? The number of digits is a little small, too much, and people are dizzy...
------ Solution --------------------
The number of microseconds is unlikely to be repeated, and you still have a random number. if you are not sure, you can add usleep (1) to wait.
However, if the server modification time is used, you cannot ensure that the number of microseconds does not repeat.
------ Solution --------------------
If you only use the timestamp (repeatable) + random number (repeatable), it cannot be guaranteed that 100% does not conflict ......
Suggestion: The time stamp (possibly repeated) + random number (possibly repeated) + Database id or other unique value (unique) can get non-repeated results.