How to Create a Random String in PHP

Below is a function and implementation of a pseudo 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.

Disclaimer: mt_rand is not considered crytographically secure and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.

Loading Conversation