RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts</strong | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.39% (5.84%*) • Fixed: 5.39% (5.84%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.69% (6.19%*) • Investment PI: 5.55% (6.02%*)

Generate a Random String With PHP

Generate a Random String With PHP

The large number of string, random, and hashing functions make it easy to generate a random string with PHP. This article, partially migrated from Internoetics, will look at just a couple ways of achieving a random string from a pool of characters, with of a defined length. Generally speaking, increasing the length of a string and character count makes the string (or password) more secure.

beliefmedia_random_string()

The first example takes a user-defined string of permitted characters and randomly selects one character at a time, concatenating each character in a loop. The function first uses mt_rand() to return a random character anchor point in our string. We then use substr() to return our random $character from the generated string.

1
<?php 
2
/*
3
 Generate a Random String With PHP
4
 http://www.beliefmedia.com/php-random-string
5
*/
6
 
7
function beliefmedia_random_string($length = 9) {
8
 
9
   $string = '';
10
 
11
   /* Allowed characters. Adjust as required. */
12
   $allowed = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
13
   $i = 0;
14
 
15
   while ($i < $length) {
16
      $char = substr($allowed, mt_rand(0, strlen($allowed)-1), 1);
17
      $string .= $char;
18
      $i++;
19
   }
20
 
21
return $string;
22
}
23
 
24
/* Usage */
25
echo beliefmedia_random_string($length = 12);
26
?>

beliefmedia_password_string()

The second function comes to us by way of the WordPress wp_generate_password() function. We've simply changed the name of the function and removed the password filter. If you're using WordPress and require a unique string, the wp_generate_password() function is almost certainly the easiest option. With the special_chars arguments as false, it selects characters from the same string as the first example. While WP uses wp_rand(), we've altered it to use mt_rand().

1
<?php 
2
/*
3
 Generate a Random String With PHP
4
 http://www.beliefmedia.com/php-random-string
5
*/
6
 
7
function beliefmedia_password_string( $length = 12, $special_chars = true, $extra_special_chars = false ) {
8
 
9
   $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
10
   if ($special_chars) $chars .= '!@#$%^&*()';
11
   if ($extra_special_chars)  $chars .= '-_ []{}<>~`+=,.;:/?|';
12
 
13
   $string = '';
14
 
15
   for ($i = 0; $i < $length; $i++) {
16
 
17
       /* WordPress uses wp_rand() rather than mt_rand() */
18
       $string .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
19
 
20
   }
21
 
22
 return $string;
23
}
24
 
25
/* Usage */
26
echo beliefmedia_password_string($length = 12);

Other than using wp_rand() instead of mt_rand(), the functions are similar in the way in which they effectively truncate a string before concatenating the last character. WordPress adds the option of $special_chars and $extra_special_chars via Boolean arguments to the mix - effectively increasing complexity and security.

The Code Explained

The first two functions use the same means of concatenating a new character: substr($chars, mt_rand(0, strlen($chars) - 1), 1);, so it's worth looking at how it works.

1
mt_rand(0, strlen($chars) - 1)

PHP's mt_rand() function will generate a random value via the Mersenne Twister Random Number Generator . It accepts two argumens: $min and $max (the latter defaulting to the platform dependent mt_getrandmax() value if not defined). We select a random value between 0 and the length of the string (strlen($chars)). We subtract 1 because we want to be able to return the last character in our string if the next function to perform its magic, substr(), returns its position. substr() considers the first value in our permitted character string (in our case, "a") as the 0th position.

1
substr($chars, $random_number, 1);

The substr() function returns part of a string specified by the start and length parameters (the length accepting a start and end position). To see how it might actually apply, and assuming mt_rand() returned a value of 9, our function would like like this: substr($chars, 9, 1);. Starting from 0, the 9th character in our string is j (we'll only return 1 character as per our third argument).

The function then loops over the string and returns a single character on each occasion until it reaches the required $length.

Example Output

Only because we did the same thing on Internoetics, here's an example random string. Each page refresh will generate a new string.

sp#-!71xiytiTo>

If you're interested, this is shortcode.

1
<?php 
2
/*
3
 Generate a Random String With PHP (Example String)
4
 http://www.beliefmedia.com/php-random-string
5
*/
6
 
7
8
  extract(shortcode_atts(array(
9
    'length' => 15,
10
    'special_chars' => true,
11
    'extra_special_chars' => true,
12
  ), $atts));
13
 
14
  /* https://developer.wordpress.org/reference/functions/wp_generate_password/ */
15
  $string = wp_generate_password($length, $special_chars, $extra_special_chars);
16
 
17
  /* Return random password */
18
  $formatted = '<font style=&quot;font-size: 25px;&quot;><strong>' . htmlentities($string) . '</strong></font>';
19
 
20
 return $formatted;
21
}
22
add_shortcode('randomstring', 'beliefmedia_random_string_example');

We've used [randomstring length="15"] to return the string. WordPress does something similar when recommending a password on account generation.

Considerations

  • There are any number of ways of producing secure strings. Read up on stackoverflow for a large number of alternatives. Many make use of inbuilt PHP7 functions. Some other examples refer to external libraries designed with more secure cryptography in mind.
  • Additional characters can be added to our first $allowed character array.

Download


Title: Generate a Random String With PHP
Description: Generate a Random String With PHP. Includes the sample WP shortcode function.
  Download • Version 0.2, 716.0B, zip, Category: PHP Code & Snippets
WordPress Shortcodes, (574.0B)    

■ ■ ■

 
Download our complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment