PHP Code

Generate random passwords with PHP

If you allow user registration on your website, you may want to be able to just randomly create and assign them an alphanumeric password. Here is the PHP function that enables you to do that. It randomly selects characters to the length that you specify (default is 8). You can use the second string to exclude characters that can be confused with other characters, such as 1 and l.

    function generatePassword($length = 8)
        $chars = 'abcdefhijklmnopqrstuvwxyzABCDEFHIJKLMNOPQRSTUVWXYZ123456789';
        //$chars = 'abdefhiknrstyzABDEFGHKNQRSTYZ23456789'; ignore confusable characters
        $numChars = strlen($chars);
        $string = '';
        for ($i = 0; $i < $length; $i++) {
            $string .= substr($chars, rand(1, $numChars) - 1, 1);
        return $string;
    echo "Welcome to our site, your temporary password is: " . generatePassword(10) . "\n";

Leave a Reply

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

To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image