With the recent backend systems I’ve been developing, I’ve often had the need to generate random text strings. These are used for password reset hashes, email confirmation hashes, unsubscribe request hashes, and everything in between. I quickly realized that a function needed to be created to handle these random text strings so here it is. This function would go in your active themes functions.php file:
function generateRandomString($length = 20) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
The above function would generate a random text string that is 20 characters long and made up of numbers, lowercase characters, and uppercase characters. In order to utilize this function within your theme, you would simply call generateRandomString(), such as:
$emailhash = generateRandomString();
Easy right?
The post Generate Random Text String – PHP/WordPress appeared first on WP Cover.