Monthly Archives

September 2010

Code Snippets: PHP Function random_string_generator

In some of my actual codebases I refer to this incorrectly as my hash generation function, which is grossly inaccurate – but I so do love the expression “Hash Code” for some reason. I do find, however, that I have nothing I could rightly use for one-way encoding to mark something with a unique string identifer, but still have the need for unique string identification.

For that reason I put together this simple PHP function which takes one variable (an integer) which determines the length of the string. The string to be generated is an Alpha-Numeric one.

Example:


$hash_code = random_string_generator(13);
echo $hash_code;
0sDf52jNfd98h

Here is the code:

//////////////////////////////////////////////////////////
// FUNCTION: random_string_generator
// ///////////////////////////////////////////////////////
// Description:
//
// This function generates a random "hash" alpha-numeric string (made of
// normal characters and numbers).
//
// If a string is passed it will be converted into an integer.
//
// The minimum size of a hash must be 1, otherwise a "hash" string
// that is one character in length will be returned.
//
// ///////////////////////////////////////////////////////
// Parameters:
//
// $length        - Length of the "hash" to be generated
//
// ///////////////////////////////////////////////////////
// Returns: string - The "hash" string
//////////////////////////////////////////////////////////
function random_string_generator($length)
{
    $charset = array('q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M');   // a-z, A-Z, 0-9

    $hash    = '';
    $index   = 0;
    $length  = intval($length);
    if (!$length || $length < 0)
    {
        $length = 1;
    }
    while ($index < $length)
    {
        $hash  = $hash . $charset[mt_rand(0, (sizeof($charset) - 1))];
        $index++;
    }

    return $hash;
}

As you can see, the character set is stored into a simple array so that characters can easily be removed and added.