Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
Web Dev + WordPress + Security

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.

About the Author
Jeff Starr = Creative thinker. Passionate about free and open Web.
Digging Into WordPress: Take your WordPress skills to the next level.

2 responses to “Get Random with PHP”

  1. Steffen Weber 2017/04/11 10:59 pm

    Old PHP functions like “rand” or “mt_rand” do not generate good random numbers. Instead, you should use the PHP 7 functions “random_int” and “random_bytes”. If you are still on PHP 5 then take a look at the random_compat package.

    • Unless you need NSA-strength security encryption, the random numbers generated by the “old” PHP functions are more than sufficient for most purposes. Even so, I wasn’t aware of the newer PHP functions and will update the article next opportunity. Thanks for the feedback.

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
Banhammer: Protect your WordPress site against threats.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.