29 Apr

PHP Code Snippet: Generate random string

I don’t code much these days but I’m happy to share this useful function I’ve built for generating random strings with optional complexity. Feel free to include this in your projects to generate IDs, referral/promo codes or complex passwords.

    /**
     * Generates a random string with optional complexity
     *
     * @param int $length random string final length
     * @param bool|int $lowerCase optional - enabled by default, use false to exclude and {int} to enforce minimum
     * @param bool|int $upperCase optional - disabled by default, use true to include and {int} to enforce minimum
     * @param bool|int $digits optional - disabled by default, use true to include and {int} to enforce minimum
     * @param bool|int $specialCharacters optional - disabled by default, use true to include and {int} to enforce minimum
     *
     * @return string
     * @throws Exception when string length and enforced minimums are in collision
     * @author mdjekic
     */
    function generateRandomString($length,$lowerCase = true,$upperCase = false,$digits = false,$specialCharacters = false)
    {
        // prepare elements
        $character_sets = array(
            'lowerCase' => 'abcdefghijklmnopqrstuvwxyz',
            'upperCase' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'digits' => '0123456789',
            'specialCharacters' => '!@#$+-*&?:'
        );

        // determine complexity
        {
            // init complexity
            $complexity = array();

            // init counter
            $counter = 0;

            // go through character sets to enforce minimums
            foreach(array_keys($character_sets) as $element)
            {
                // reference minimum
                $minimum = $$element;

                // check if disabled
                if($minimum === false)
                {
                    // completely remove the character set from the game
                    unset($character_sets[$element]);
                }
                else
                {
                    // set complexity
                    $complexity[$element] = ($minimum === true) ? 0 : $minimum;
                }

                // update counter
                $counter += ($complexity[$element] == -1) ? 0 : $complexity[$element];
            }

            // make sure length and counter are not in collision
            if($length < $counter) throw new Exception("Random string length must be bigger than the sum of enforced minimums of it's elements.");

            // calculate room left for improvisation after minimums are applied
            $improvisation = $length - $counter;

            // improvise leftover counts
            while($improvisation > 0)
            {
                // create a random number of characters within the improvisation space
                $number = rand(1,$improvisation);

                // update character set minimum for a random character set
                $complexity[array_rand($character_sets)] += $number;

                // decrease room for improvisation
                $improvisation -= $number;
            }
        }

        // init string
        $string = array();

        // go through all character sets
        foreach ($character_sets as $character_set => $characters)
        {
            // append the number of characters determined by complexity
            for ($i = 0; $i < $complexity[$character_set]; $i++)
                $string[] = $characters[rand(0,strlen($characters)-1)];
        }

        // randomize and return
        shuffle($string);
        return implode('', $string);
    }

Inspired by Salman Arshad’s effort this function enables you to toggle usage of lower case and upper case letters, digits and special characters. You can also set minimums for each category. That’s pretty neat, right?

Here’s an example:

/**
 * Generate a random string with 8 characters in total,
 * a minimum of 2 lower case letters and 2 digits. Include
 * upper case characters and don't include special characters.
 */
generateRandomString(8,2,true,2,false);

And some output variations:

7tX7217e
toMh298u
P9he1123
975o6Gj2
d85RUeLN
Tcm47TYW
ds6zpa1o
j85c8582
7TBz967e
3cg2zpux

Enjoy 🙂

Share on TumblrTweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditPin on PinterestShare on VK

Leave a Reply

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

Copyright: Miloš Đekić