How can I generate a 7-character alphanumeric key?

6

How can I generate a key with 7 alpha-numeric characters, completely random in PHP?

In other words, I want to make a key with completely random numbers and capital letters.

I've tried using the rand, but the rand only generates numbers.

    
asked by anonymous 07.07.2016 / 04:52

4 answers

10

The safest method to generate a pseudorandom combination is to use random_bytes() .

In this way use as follows:

$numero_de_bytes = 4;

$restultado_bytes = random_bytes($numero_de_bytes);
$resultado_final = bin2hex($restultado_bytes);

This will generate a combination of 8 characters, pseudo-random.

To pass to uppercase use strtoupper , as strtoupper($resultado final) . To remove one of the characters, in order to make it 7 instead of 8, use substr() , thus substr($resultado_final, 1) .

Resulting in:

$resultado_final = strtoupper(substr(bin2hex(random_bytes(4)), 1));
  

This function is available in PHP 7 (and above) for use in older versions see in this implementation .

    
07.07.2016 / 05:07
3

Here is another alternative to generating a pseudo-random string with 7 characters, including uppercase, lowercase, and numbers:

$upper = implode('', range('A', 'Z')); // ABCDEFGHIJKLMNOPQRSTUVWXYZ
$lower = implode('', range('a', 'z')); // abcdefghijklmnopqrstuvwxyzy
$nums = implode('', range(0, 9)); // 0123456789

$alphaNumeric = $upper.$lower.$nums; // ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
$string = '';
$len = 7; // numero de chars
for($i = 0; $i < $len; $i++) {
    $string .= $alphaNumeric[rand(0, strlen($alphaNumeric) - 1)];
}
echo $string; // ex: q02TAq3
    
07.07.2016 / 11:13
1

sprintf and mt_rand

Another short and simple option would be combining mt_rand with sprintf .

sprintf('%07X', mt_rand(0, 0xFFFFFFF))

In this case, I'll explain:

mt_rand will generate a number from 0 to 0xFFFFFFF (which is equivalent to an int 268435455).

sprintf formats a value according to a specific parameter. I used the %X modifier, which forms a value for a hexadecimal number (the uppercase X means that the letters are uppercase, if you want lowercase you can use %x ). However, before X there is a 7 number %. This means that the value that will be formatted in the second parameter of sprintf must contain 7 characters or more. And finally, 0 before 7 means that, when it does not have 7 characters, it will be filled with 0 .

Then, briefly explaining:

'%' - curinga do modificador
'0' - o número a ser preenchido quando faltar
'7' - quantidade especificada para formatação
'X' - formatada para hexadecimal, com letras maiúsculas (pode ser trocado para 'x')

str_shuffle , str_repeat and substr

The str_shuffle function of PHP is intended to mix a given string . With applied intelligence, you can also produce good results through it.

In my example, I created a list of characters from a to z and 0 to 9 . I used str_repeat to repeat the list of characters. Then I used substr to reduce 7 .

Example:

    $ascii = implode('', array_merge(range('a', 'z'), range(0, 9)));

    $ascii = str_repeat($ascii, 5);

    substr(str_shuffle($ascii), 0, 7);

You can also use a function called random_bytes , but you may have to work with value conversions, since the values returned by it are characters that go beyond alpha-numeric. You can specify through the first parameter how many bytes you want:

     openssl_random_pseudo_bytes(7) // dJ─Å(\x01"

One last option would be to use dechex(mt_rand(0, 0xfffffff))

    
07.07.2016 / 13:46
1

Some time ago I came to this function:

function generateRandomString($size = 7){
   $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuwxyz0123456789";
   $randomString = '';
   for($i = 0; $i < $size; $i = $i+1){
      $randomString .= $chars[mt_rand(0,60)];
   }
   return $randomString;
}
    
07.07.2016 / 11:35