Generate Random String in PHP

Developing a modern PHP web application comes with a common requirement to generate random strings for various reasons. Learn different methods to generate random strings in PHP with example code snippets.

Generate Random String in PHP

PHP provides multiple ways to generate PHP random string which can be used for authentication tokens, as API keys, for password reset links, session identification, invitation links, or unique filenames. In this post we will learn how to generate random strings in PHP with explanation and code snippets.

 

When to Generate Random Strings?

Random string generation can serve various purposes in web application development. Most common reasons random strings are needed for are:

  • To generate random and secure token for authentication.
  • For session identifiers to identify unique sessions.
  • To create random password.
  • To generate verification tokens for email verification.
  • For API keys to validate API requests.
  • Unique identifiers and captcha strings.
  • For unique filenames for temporary files.

It is important to choose the right method which aligns with code simplicity, performance and application security.

 

How to Generate Random Strings in PHP (Simple Methods)

It is easy to generate random string using default/built-in functions PHP offers for string manipulation. Following are recommended and most commonly used methods to generate random strings in PHP applications. Some of these methods cryptographically secure randomness which is ideal for tokens, passwords and API keys.

 

Method 1: Using substr() with str_shuffle()

This method is the simplest and easiest way to generate random string and it is easy to understand. However this method is not cryptographically secure and str_shuffle() may produce predictable patterns.

substr(str_shuffle($characters), 0, $length);
 

Method 2: Using bin2hex() with random_bytes()

This method is cryptographically secure and can be used to generate secure token in PHP with ease. The only downside is that it will generate hexadecimal characters i.e.(0-9, a-f) and it will require to handle character set limitation for full alphanumeric string support.

bin2hex(random_bytes($length / 2));
 

Method 3: Using bin2hex() with openssl_random_pseudo_bytes()

This method is considered an alternative of random_bytes() and can be used as secure approach to create random passwords in PHP.

bin2hex(openssl_random_pseudo_bytes($length));
 

Method 4: Using rand() with sha1() hashing

This method can be used for non-critical purposes when security is not the concern like to create random string in PHP for filenames. This method generates SHA-1 hash of pseudo characters using the rand() function.

sha1(rand());
 

Method 5: Using For Loop

This method uses random_int() which is a secure approach and this method gives more control over character-set by providing the characters of developer's choice.

$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

$random_string = '';

for ($i = 0; $i < $length; $i++) {
$random_string .= $characters[random_int(0, strlen($characters) - 1)];
}

We demonstrated different methods to generate random strings in PHP. It is very easy to generate random strings once you know the tools. For non-critical strings str_shuffle() should be enough but for security of application random_bytes() and random_int() should always be used which many modern applications rely on.