PHP Code Snippets
Below are some useful PHP code snippets for use in everyday projects.
Here is an example of how to generate a random number between two values, in this case 1 and 59, then display it.
<?php // Minimum and maximum values for random number. $minVal = 1; $maxVal = 59; // Generate random number. $randomNumber = rand($minVal, $maxVal); // Display the result. echo $randomNumber; ?>
Here, a random password is generated from a specified set of characters. The length of the password is also randomly selected from a given minimum and maximum length.
<?php // Possible characters in password. $alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $numbers = '0123456789'; $nonAlpha = '{]+-[*=@:)}$^%;(_!?>/|.'; // Put possible password characters into a character array. $charSet = str_split($alpha . $numbers . $nonAlpha); // Minimum and maximum password length. $minLength = 20; $maxLength = 30; // Select a random password length between the minimum and maximum. $length = rand($minLength, $maxLength); // Array for new paasword. $result = []; // Construct new password. for ($i = 0; $i < $length; $i = $i + 1) { // Select a random character from the possible characters array. $selected = $charSet[rand(0, sizeof($charSet)-1)]; // Add the chosen character to the new password. array_push($result, $selected); } // Display the password. echo join($result); ?>