Goal: Generate a Random String with PHP

Difficulty: Easy

Estimated Time: Seconds

Prerequisites: PHP

Below is a function and implementation of a random string generator using PHP. Since PHP does not have it's own random string generator, we need to specify the allowed characters for our random string. In this example I have limited my random strings to Alpha-Numeric characters, but you can easily add your own.

function generateRandomString($length){ 
    $characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $charsLength = strlen($characters) -1;
    $string = "";
    for($i=0; $i<$length; $i++){
        $randNum = mt_rand(0, $charsLength);
        $string .= $characters[$randNum];
    }
    return $string;
}

Now if you want to generate a random string in your code you just drop this function in and you can call the function by doing something like echo generateRandomString(5); which will echo to the screen a random string of 5 characters long.

Comments

Leave a Reply



(Your email will not be publicly displayed.)



Search