Generate Random Text String – PHP/WordPress


About The Author
Avatar Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







Generate Random Text String – PHP/WordPress

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?


Share Your Thoughts

Leave a Reply

Your email address will not be published. Required fields are marked *


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!