sepehr
12/6/2014 - 6:14 PM

PHP: Random string helpers

PHP: Random string helpers

<?php

if ( ! function_exists('random_string'))
{
	/**
	 * Generates random string.
	 *
	 * @param  string  $type Type of random string to generate.
	 * @param  integer $len  Desired length of output string.
	 *
	 * @return string
	 */
	function random_string($type = 'alnum', $len = 8)
	{
		switch($type)
		{
			case 'basic':
				return mt_rand();

			case 'alnum':
				return random_string_from_pool('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', $len);

			case 'numeric':
				return random_string_from_pool('0123456789', $len);

			case 'nozero':
				return random_string_from_pool('123456789', $len);

			case 'alpha':
				return random_string_from_pool('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', $len);

			case 'md5':
			case 'unique':
				return md5(uniqid(mt_rand()));

			case 'sha1':
			case 'encrypt':
				return sha1(uniqid(mt_rand(), TRUE));

			case 'human':
			case 'voweled':
			case 'human-readable':
				$string     = '';
			    $vowels     = array('a','e','i','o','u');
			    $consonants = array(
			        'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm',
			        'n', 'p', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'
			    );

			    $max = $len / 2;
			    for ($i = 1; $i <= $max; $i++)
			    {
			        $string .= $consonants[mt_rand(0, 19)];
			        $string .= $vowels[mt_rand(0, 4)];
			    }

			    return $string;
		}
	}
}

// ------------------------------------------------------------------------

if ( ! function_exists('random_string_from_pool'))
{
	/**
	 * Generates random string from the provided pool.
	 *
	 * @param  string  $pool Character pool string.
	 * @param  integer $len  Desired length of output string.
	 *
	 * @return string
	 */
	function random_string_from_pool($pool, $len = 8)
	{
		$string   = '';
		$pool_len = strlen($pool) - 1;

		for ($i = 0; $i < $len; $i++)
		{
			$string .= substr($pool, mt_rand(0, $pool_len), 1);
		}

		return $string;
	}
}

/* End of file string_helper.php */