Random Password (String) Generator for PHP

Written by Mark Sanborn: Dec 2, 2008

Random string generators are something we programmers end up using quite a bit. Sometimes you want to generate a random file name, a random email verification link, a random password, random token, etc.. Here is the one that I have been using lately.

This password generator uses the Mersenne Twister algorithm to generate random digits. You can learn more about it at Wikipedia or on Makoto Matsumoto’s website.

    <?php
    function randomString($length = 10, $chars = '1234567890') {
    
        // Alpha lowercase
        if ($chars == 'alphalower') {
            $chars = 'abcdefghijklmnopqrstuvwxyz';
        }
    
        // Numeric
        if ($chars == 'numeric') {
            $chars = '1234567890';
        }
    
        // Alpha Numeric
        if ($chars == 'alphanumeric') {
            $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
        }
    
        // Hex
        if ($chars == 'hex') {
            $chars = 'ABCDEF1234567890';
        }
    
        $charLength = strlen($chars)-1;
    
        for($i = 0 ; $i < $length ; $i++)
            {
                $randomString .= $chars[mt_rand(0,$charLength)];
            }
    
        return $randomString;
    }
    
    echo randomString(8,'numeric');
    ?>

Syntax is randomString([int],[predifined | custom char set]);

For example to create an 8 character alpha numeric string you could use:

randomString(8,'alphanumeric');

Of if you wanted a string with only a small subset of characters you could use:

randomString(8,'abco0iLlI');

Do you use something similar?

Need to print shipping labels on your site?

Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.

Share: