dimanche 24 mai 2015

Create keys randomly with PHP

I have an mobile app that request a key in my server, The key structure contains 7 characters as follows:

@ + [0-9] + [0-9] + [0-9] + [A-Z] + [A-Z] + [0-9] 

@876EU8, @668KI2 .......

Whereas the key initially has seven characters, in this case three numbers, two letters and one number, doing the math this gives a maximum of 676,000 keys.

To gerate this keys I'm using this code in PHP:

function generateRandomString($length = 2) {
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

$randomKeyNumber = rand(100,999);
$randomKeyLetter = generateRandomString();
$randomKeyLast = rand(0,9);

$randomKey = "#".$randomKeyNumber.$randomKeyLetter.$randomKeyLast;//Returns a key like @876TG9 

The next code check if the key exists inside the database, If exists he random another key, if not he insert the key in database and return this key to my app

This code works perfectly, but assuming the system has already generated a total of 650,000 keys, in the case of this code it would always generate the same keys, and the likelihood of it generate a key that does not exist yet is very small.

How can I solve this problem and avoid future problems? (There is no problem in creating the keys in an orderly manner, eg 000AA0, 000AA1, 000AA2, 000AA3 .... 999ZZ9)




Aucun commentaire:

Enregistrer un commentaire