Get Random with PHP

This tutorial explains numerous ways to get random items via PHP: numbers, strings, passwords, nonces, images, and more. I use these techniques in various projects, and want to round them all up in one place for easy reference. I’ll be updating this post with additional techniques as I get them.

Get a random number

This technique is useful for appending random numbers to assets like CSS and JavaScript files.

function shapeSpace_randomizer() {
	return rand(1000000,9999999);
}

Usage:

$random_number = shapeSpace_randomizer();

This is just one way of going about it. The returned number will be something between the two specified numbers. You can adjust the range as desired.

Get a random string

If you need a random alphanumerical string, try this handy function:

function shapeSpace_random_string($length) {
	
	$characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";	

	$strlength = strlen($characters);
	
	$random = '';
	
	for ($i = 0; $i < $length; $i++) {
		$random .= $characters[rand(0, $strlength - 1)];
	}

	return $random;
	
}

Usage:

$random_string = shapeSpace_random_string(10);

That gets you a random string of 10 characters. Change the 10 to whatever is needed. Here is an alternate version of the function:

function shapeSpace_random_string($length) {
	
	$characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	
	$random = substr(str_shuffle($characters), 0, $length);

	return $random;
	
}

Usage is the same as the previous function.

Even more random string

This technique is similar to the previous, but attempts to make the alphanumeric string even more random by seeding the random number generator with the srand() function.

function shapeSpace_random_string($length) {
	 
	$characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	
	srand((double)microtime()*1000000); 
	
	$random = '';
	
	for ($i = 0; $i < $length; $i++) {  
		$random .= $characters[rand() % strlen($characters)];  
	}
	
	return $random;
	  
}

Usage:

$random_string = shapeSpace_random_string(10);

That gets you a random string of 10 characters. Change the 10 to whatever is needed.

Random human-readable string

Here we are generating a random string that includes only letters, in such a way as to make the string readable by human visitors.

function shapeSpace_random_string_readable($length) {
	
	$c = array('b','c','d','f','g','h','j','k','l','m','n','p','r','s','t','v','w','x','y','z');
	
	$v = array('a','e','i','o','u');
	
	srand((double)microtime()*1000000);
	
	$max = $length / 2;
	
	$random = '';
	
	for ($i = 1; $i <= $max; $i++) {
		$random .= $c[rand(0,19)];
		$random .= $v[rand(0,4)];
	}
	
	return $random; 
	 
}

Usage:

$random_string = shapeSpace_random_string_readable(10);

That gets you a random, human-readable string of 10 characters. Change the 10 to whatever is needed. I forget where I found this technique, so let me know if you know the original source.

Get random items from array

There are many ways of going about this. The goal is to return a random selection of items from an array. I use this technique for displaying four random advertisements (from an array that includes eight ads).

function shapeSpace_get_random_items($length) {
	
	$items = array(
		'item 1',
		'item 2',
		'item 3',
		'item 4',
		'item 5',
		'item 6',
		'item 7',
		'item 8',
	);
	
	$n = array(1, 2, 3, 4, 5, 6, 7, 8);
	
	srand((double)microtime()*1000000);
	
	$rand = array_rand($n, $length);
	
	sort($rand);
	
	$random = '';
	
	foreach ($rand as $r) $random = $items[$r] .' ';
	
	return $random;
	
}

Usage:

$random_string = shapeSpace_get_random_items(4);

That gets you a string that contains four random items separated by a space. You can adjust the number as desired, just keep it less than the total number of items in your array. You can customize the output string as desired.

Random password strings

Here is an example of using PHP’s random functionality to generate passwords.

function generatePassword($length=9, $strength=0) {
    $vowels = 'aeuy';
    $consonants = 'bdghjmnpqrstvz';
    if ($strength & 1) {
        $consonants .= 'BDGHJLMNPQRSTVWXZ';
    }
    if ($strength & 2) {
        $vowels .= "AEUY";
    }
    if ($strength & 4) {
        $consonants .= '23456789';
    }
    if ($strength & 8) {
        $consonants .= '@#$%';
    }
 
    $password = '';
    $alt = time() % 2;
    for ($i = 0; $i < $length; $i++) {
        if ($alt == 1) {
            $password .= $consonants[(rand() % strlen($consonants))];
            $alt = 0;
        } else {
            $password .= $vowels[(rand() % strlen($vowels))];
            $alt = 1;
        }
    }
    return $password;
}

There are many ways to generate random passwords, but this technique is nice because you can control the password’s strength and length. Here is a usage example:

$password = generatePassword(18, 8);

For more information, check out the source article.

Get known random string

This is sort of a weird one that I wouldn’t recommend on a live site. I was experimenting with simple ways of stopping spam on my public chat plugin, and decided to try an Ajax-powered nonce field. Here is the code that I used to generate the nonce (hidden input):

$nonces = array(
	'Y4-B84pY:IN:;th1H$r+O8cF',
	'IA/,HwsA^y@V0Rre(jF](^P+',
	'kW5oJsj,M4$.}?Zf/GqqZcaz',
	'=1ekfx)K#_5goJ6HrifbK=Ss',
	'8#8r)z3=ELR;7Oqwcp3V3Nv!',
	'Ei9)OuJaqYRssa]b}wut3;=m',
	'}TM42oi:-HppFF:XYk0OY{DM',
	'z%v3[oRX[:w1pp,3ODHD)m7O',
	'@.,oe/A3KKJAvdtSc{]kogMA',
	'tR7djZB~)hlqs6U*jTcXT+IS',
);

$random = array_rand($nonces, 1);

$nonce = isset($nonces[$random]) ? base64_encode($nonces[$random]) : 0;

echo '<input type="hidden" name="sac_js_nonce" value="'. $nonce .'" />';

Then when processing the Ajax request, I can verify the user by checking the submitted nonce value against the known set of $nonces.

Note that this technique isn’t really recommended; I include it here because it fits the topic, and because it may help generate some ideas for those who may be working on similar projects.

Display a random image

Last but not least, here is a tutorial that explains how to display random images via PHP.