2

I want to build a token number generator. In each call, a random and unique 8-digit number should be returned. I am using PHP and MySQL. In MySQL I'll have a table where I will insert the new serial, each time it will be generated.

How can I generate new numbers in each call?

Tokens will be used from end-users to activate software (and will expire, e.g. after 1 week). So, I need tokens to be unique and not sequential. This describes better my needs. Token format will be just numbers, so that it can be easily spelled and typed.

Even if tokens expire, I do not want to generate an already generated token at a later time.

Thank you

8
  • use Mysql auto increment and start with 10,000,000. Commented Jan 15, 2013 at 0:06
  • is this valid 11223344? or all numbers are unique 12345678? Commented Jan 15, 2013 at 0:08
  • 1
    @ROYFinley, although that would generate unique id's they could hardly be described as random Commented Jan 15, 2013 at 0:08
  • Technically, the phrase "serial number" means a number that increases as a series. ie not random. Commented Jan 15, 2013 at 0:13
  • 1
    "Random", "unique" and "an unknown number of" (implied by the question) in the same sentence does not make sense. In all likelihood you want unpredictable and unique. Commented Jan 15, 2013 at 1:05

2 Answers 2

3

Ok, so this code does not put the serial number into a database but it will return a serial number 8 digits long. If you want just numbers change the allowed characters variable to just numbers.

<?php function generate_serial_number() { $Allowed_Charaters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; return substr(str_shuffle($Allowed_Charaters), 0, 8); } ?> 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the generator, but this does not fulfills the number-unique requirement. Of course, I can insert it in the db until I get no error (due to the unique definition of the relative column).
0

I usually use http://php.net/manual/en/function.uniqid.php with the more_entropy parameter to true.

2 Comments

That sounds good, but how can we get rid of the alphas in there?
Strip them. Use preg_replace(). But beware, you can have collisions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.