Plugin Sale! Save 15% on pro plugins with discount code: NEWYEAR2021
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);


$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;


$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";
	$random = '';
	for ($i = 0; $i < $length; $i++) {  
		$random .= $characters[rand() % strlen($characters)];  
	return $random;


$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');
	$max = $length / 2;
	$random = '';
	for ($i = 1; $i <= $max; $i++) {
		$random .= $c[rand(0,19)];
		$random .= $v[rand(0,4)];
	return $random; 


$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);
	$rand = array_rand($n, $length);
	$random = '';
	foreach ($rand as $r) $random = $items[$r] .' ';
	return $random;


$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(

$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.

Jeff Starr
About the Author
Jeff Starr = Fullstack Developer. Book Author. Teacher. Human Being.
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.

    • Jeff Starr

      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.
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 »
The Tao of WordPress: Master the art of WordPress.
Simply Static is my go-to plugin for generating static HTML versions of WordPress sites. Works flawlessly.
Note to self: never, ever, ever buy any CD or DVD from eBay. Every single time the discs are scratched, damaged, missing, fake, or worse. Never again you clowns.
Find out if a plugin works with the latest version of WordPress @
Going through all of my data, deleting all the chaff. Going for less than 500 GB total data storage.
Finally deleted all the cool unused placeholder Twitter accounts that I signed up for years ago. I will never use them.
After several years with Dashlane, I've moved on to a simpler, better solution.
After 10+ years, finally moved the last of my sites away from Media Temple.
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.