In some cases, we find ourselves with the need to create a set of alphanumeric characters for a specific later use. A common use could be to generate a random password in a new registration on your website.
First, we create two variables that you can customize to your needs.
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$longword=8;
You can customize the length of the password to be generated with the $longword variable, and the characters that will make up the password in the $characters variable.
Next, we create a loop to get a random value each loop and stop when we get the desired length.
for($pass='', $n=strlen($chars)-1; strlen($pass) < $longword ; ) {
$x = rand(0,$n);
$pass.= $chars[$x];
}
To achieve the result, we have used the for loop method offered by PHP, being one of the most complete cycles, since it allows us to use three expressions in its syntax.
Syntax of a for loop:
for (expression1; expression2; expression3) {
judgment
}
- The first expression will be executed only once at the beginning of the loop. It can contain multiple expressions separated by commas.
- The second expression will be evaluated before starting the loop, if its value obtained is TRUE the loop will be executed until the value obtained is FALSE. In the case of having several expressions separated by commas, only the value of the last expression will be taken into account.
- The third expression will be executed every time the loop is finished. It can contain multiple expressions separated by commas.
If you look at the code, in the first expression we use it to create the empty variable that will store our generated password, and to count the characters with the function strlen() from which we subtract a value by adding -1 since when we use the text string later, the first character, as happens with an array, corresponds to the number 0 and not the number 1. For example, we can count 20 characters but in the variable they will be assigned from 0 to 19, and not from 0 to 20, which would add up to 21.
In the second expression of the code, we take the opportunity to put our condition.
Within the statement, the function rand() will give us a random number from 0 to the number of characters available, which we will use to add the value to the variable where we store our password.
We can now use our password stored in the $pass variable.
The complete code would be:
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$longword=8;
for($pass='', $n=strlen($chars)-1; strlen($pass) < $longword ; ) {
$x = rand(0,$n);
$pass.= $chars[$x];
}
print 'Our obtained password is: ' . $pass;
