Create random strings in PHP

I made a PHP function which returns a random string using Alphabets [a to z] and [A to Z], Numbers [0 to 9]. It is very easy to use and can be easily modified.

 * Create a random string using PHP
 * @author	php-tricks
 * @param $length the length of the string how long you want to create
 * @return $string as a result of random string
function generateRandomString($length = 6) {
	$string = "";
	$valid_characters = array_merge(range('A','Z'), range('a','z'), range('0','9'));
	$max = count($valid_characters) - 1;
	for ($i = 0; $i < $length; $i++) {
		$rand = mt_rand(0, $max);
		$string .= $valid_characters[$rand];
	return $string ;

How to call it ??

/* Calling above function */
echo generateRandomString(12);
// Here you will get random string length of 12 characters.

Note: You can remove any of the ranges in $valid_characters (For e.g. if you do not want uppercase letters in random string then delete the range('A','Z')) or you can put you own array of custom characters.

By Ashutosh Pratap

I am software developer by profession and doing work and research in field of Computer programmings like PHP, WordPress, Magento, jQuery, Google APIs and many more web languages. Apart from this I write blogs on programming languages like PHP, Javascript, WordPress etc. I am also individual and independent Freelancer so you can hire me for your web work.

Leave a comment

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