How to generate random password with PHP?

Just build a string of random a-z, A-Z, 0-9 (or whatever you want) up to the desired length. Here’s an example in PHP:

function generatePassword($length = 8) {
    $chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $count = mb_strlen($chars);

    for ($i = 0, $result=""; $i < $length; $i++) {
        $index = rand(0, $count - 1);
        $result .= mb_substr($chars, $index, 1);
    }

    return $result;
}

To optimize, you can define $chars as a static variable or constant in the method (or parent class) if you’ll be calling this function many times during a single execution.

Leave a Comment