Generating random but unique numbers for the link id

I want to generate unique numbers so that I can use them as reference numbers to process my client requests.

I don't want numbers to be repeated and I am not using any kind of database to store numbers.

I just want to use a simple algorithm to generate random numbers.

I am using something like

rand(10*45, 100*98)

Is it possible to do something like this. I know my requirement seems rather strange, but I just want to know if this is possible.

+3


source to share


3 answers


Why not just preface a random number with a Unix timestamp? This will ensure uniqueness.

$random = time() . rand(10*45, 100*98);

      



Otherwise, you can keep your numbers in a file. If you can, save them to the database.

+6


source


Why not use this function, php provides for this purpose:

uniqid



Example:

uniqid(rand(10*45), true)

      

+4


source


If you accept hexadecimal numbers then:

function random_id($bytes) {
    $rand = mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM);
    return bin2hex($rand);
}
echo random_id(5); // Ex: a06e0e4e72

      

5 bytes (i.e. 40 bits) creates about 2 40 (about a trillion) possible unique values. It must be more than random in order to generate many unique identifiers.

+2


source







All Articles