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 numbers and uppercase letters completely random.
I’ve tried using Rand, but Rand only generate numbers.
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 numbers and uppercase letters completely random.
I’ve tried using Rand, but Rand only generate numbers.
12
The safest method to generate a pseudo-random combination is by using the random_bytes()
.
So 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 switch to uppercase use the strtoupper
, as strtoupper($resultado final)
. To remove one of the characters, to make it 7 instead of 8, use the 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), to use it in older versions see in this implementation.
We are currently going in which version of PHP?
The latest version is 7.0.8.
I’ll test, one moment.
4
A while ago I arrived at 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;
}
Simple but well functional function. Excellent!
4
sprintf
and mt_rand
Another short and simple option would be matching mt_rand
with sprintf
.
sprintf('%07X', mt_rand(0, 0xFFFFFFF))
In case I explain:
mt_rand
will generate a number of 0 until 0xFFFFFFF
(equivalent to an int 268435455).
sprintf
format a value according to a specific parameter. I used the modifier case %X
, that formats a value for a hexadecimal number (uppercase X means the letters will be uppercase, if you want lowercase you can use %x
).However, before the X
there is a number 7
. This means that the value that will be formatted in the second parameter of sprintf
shall contain 7
characters or more. And finally, the 0
before the 7
means that when it is not 7 characters long, it will be filled in with 0
.
So, 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 function str_shuffle
PHP’s purpose is to mix a certain 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 character list. Then I used substr
to reduce the 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 the 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))
3
Here is another alternative to generate a 7-character pseudo-random string, including uppercase, minuscule, and number:
$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
-2
<?php
function chaveAlfaNumerica($QuantidadeDeCaracteresDaChave){
$res = implode('', range('A', 'z')); // ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxiz
$con = 1;
$var = '';
while($con < $QuantidadeDeCaracteresDaChave ){
$n = rand(0, 57);
if (($n == 26) || ($n == 27) || ($n == 28) || ($n == 29) || ($n == 30) || ($n == 31)){
}else{
$var = $var.$n.$res[$n];
$con++;
}
}
return substr($var, 0, $QuantidadeDeCaracteresDaChave);
}
//chamando a função.
echo chaveAlfaNumerica(3);
//retorna a chave com a quantidade passada no parametro.
?>
I created this function that creates a random key in php,
Browser other questions tagged php
You are not signed in. Login or sign up in order to post.
strtoupper(substr(md5(date("YmdHis")), 1, 7));
– William Novak
That’s right William, but how do I put the letters in uppercase?
– Gonçalo
Opá ! I just edited my comment and added the function
strtoupper
– William Novak
Thanks! I had already seen on google this Function however but thank you very much for the help, if you want to post as answer, to give quotation.
– Gonçalo
I believe William’s suggestion does not fully answer the question, since it is not random, as prompted in "completely random". This is making an MD5() based on the current date. In other words it is possible to guess the code since it only captures the first 7 characters of the date MD5. It appears to be random because it always has a different "second", thus generating a new MD5, but time is not random. Also if you use the date() for the date/time of Brasilia/BR, collision will occur when leaving/entering the daylight saving time, after all the time will repeat. : S
– Inkeliz
Just be aware that random does not mean single. Generating random code within the proposed condition is simple. The tricky thing is to generate unique strings. Note that encrypting with MD5, as an example posted and cut the final string is quite insecure as it exponentially increases collisions.
– Daniel Omine
If the question with 4 votes answers the question, it would be nice to tag [tag:php-7]
– Wallace Maxters