|
Post by Leon Grad on Aug 14, 2021 14:42:47 GMT
How can I create a random string with PHP? I'd like it to be 10 alphanumerical characters long. So, just "0" to "9", and "a" to "z". Is there anything like:
<?php
$random_string = RANDOM(10);
echo $random_string;
?> I know the code above doesn't work, and I want a PHP code that's portable and doesn't require the client to link to any library.
|
|
|
Post by John Skieswanne on Aug 15, 2021 14:42:47 GMT
There are no native functions, in PHP, to generate a random alphanumerical string.
However there is the shuffle option, which takes a pre-existing string, and randomly re-orders the characters within such a string.
Also, we have the substr option, which extracts a segment of any characters length (including 10) of a string.
Combining the two, we could write:
$alphanumerical_list = 'abcdefghijklmnopqrstuvwxyz1234567890'; //string contains all desired alphanumerical characters $shuffled = str_shuffle($alphanumerical_list); //shuffles the characters in the string $alphanumerical_list $random_string = substr($shuffled, 0, 10); //selects only the first 10 characters from $shuffled
echo $random_string;
However the output string, though random, will only contain a given character once; meaning, such a character cannot repeat within the random string. This increases the likelihood of a brute force attack, and makes the string less than optimal, randomness-wise. The solution, of course, is simple: since the random string will be 10 characters long, multiply the occurrence of all characters in alphanumerical_list 10 times, so there are 10 "a", 10 "b", etc.
Therefore, all characters in the string will be likely to repeat, up to the length of the string. The complete, improved code is given below:
$alphanumerical_list = 'abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890'; //string contains 10 sets of desired alphanumerical characters $shuffled = str_shuffle($alphanumerical_list); //shuffles the characters in the string $alphanumerical_list $random_string = substr($shuffled, 0, 10); //selects only the first 10 characters from $shuffled
echo $random_string;
|
|