Scriptbaker
SCRIPTBAKERAI & Software Engineering
Engineering

Random string generator

Learn how to generate random strings in PHP with a simple, reusable function. This guide explains how the generator works, how to create strings of different lengths, common use cases, and secure alternatives using random_bytes() and random_int() for authentication tokens and other security-sensitive applications.

· 5 min read · By Tahir Yasin

Random String Generator in PHP

Random strings are commonly used in web applications to create temporary identifiers, unique keys, reference codes, tokens, filenames, and other values that should not be predictable or easily duplicated.

In PHP, you can create a random string generator function that accepts a desired length and returns an alphanumeric string. This can be useful when you need a quick way to generate random values for application logic.

In this guide, we’ll look at a simple PHP random string generator, explain how it works, discuss common use cases, and cover more secure approaches when randomness is important for authentication or security.

PHP Random String Generator

The following function generates an alphanumeric random string. By default, it generates a 10-character string, but you can pass any desired length to the function.

function generate_string($length = 10) {    $chars = array_merge(range(0, 9), range('A', 'Z'), range('A', 'Z'));    shuffle($chars);    $string = implode(array_slice($chars, 0, $length));    return $string;}

How to Generate a Random String

Once the function has been defined, call it by passing the number of characters you want to generate.

$randomString = generate_string(15);echo $randomString;

The result will be a random alphanumeric string such as:

7K2M9QX4AB8PL6C

Because the value is generated randomly, the exact output will be different each time the function is executed.

Generate a 10-Character Random String

If you don't provide a length, the function uses its default value of 10 characters.

echo generate_string();

For example, the function might return:

8F2KQ7A1XZ

Generate a Random String of a Specific Length

You can specify the required string length by passing an integer to the function.

echo generate_string(20);

This generates a random string containing up to 20 characters from the character set used by the function.

You can change the number according to your application's requirements:

generate_string(5);generate_string(10);generate_string(25);generate_string(50);

How the Random String Generator Works

The function uses several PHP functions to build the random string.

1. Create the Character Set

The range() function creates arrays containing numbers and uppercase letters.

range(0, 9)

This produces numbers from 0 through 9.

range('A', 'Z')

This produces uppercase letters from A through Z.

The arrays are then combined using array_merge():

$chars = array_merge(    range(0, 9),    range('A', 'Z'),    range('A', 'Z'));

2. Shuffle the Characters

The shuffle() function randomly rearranges the elements of the array.

shuffle($chars);

This means the order of the available characters changes each time the function is executed.

3. Select the Required Characters

array_slice() is used to take the required number of characters from the shuffled array.

array_slice($chars, 0, $length)

For example, if $length is 10, the function takes the first 10 elements from the shuffled array.

4. Convert the Array into a String

Finally, implode() combines the selected characters into a single string.

$string = implode(array_slice($chars, 0, $length));

The resulting value is returned by the function.

Common Uses of Random Strings

Random strings have many practical applications in PHP and web development. Some common examples include:

  • Generating temporary identifiers
  • Creating unique reference numbers
  • Generating temporary filenames
  • Creating order or transaction references
  • Generating invitation codes
  • Creating non-sensitive record identifiers
  • Generating test data
  • Creating temporary values for application workflows

Random Strings for Database Records

A random string can be used as an application-level identifier for a database record. For example, instead of exposing a sequential numeric ID in a URL, an application may use a random-looking reference.

$reference = generate_string(12);echo $reference;

However, generating a random string does not automatically guarantee uniqueness. If the application requires guaranteed unique database identifiers, consider using a database UNIQUE constraint and handling collisions appropriately.

Random String Generator with Lowercase and Uppercase Letters

If your application requires both uppercase and lowercase characters, you can create a custom character set.

function generate_string($length = 10) {    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';    $string = '';    for ($i = 0; $i < $length; $i++) {        $string .= $characters[random_int(0, strlen($characters) - 1)];    }    return $string;}

This version uses random_int(), which is preferable when the generated value needs stronger randomness.

Secure Random String Generation in PHP

It is important to choose the random-generation method based on how the resulting string will be used.

For security-sensitive values such as password-reset tokens, email-verification tokens, API secrets, session-related tokens, or authentication links, a predictable random-number generator should not be used.

PHP provides random_bytes() for generating cryptographically secure random bytes. These bytes can be converted to a hexadecimal string when a readable token is required.

$token = bin2hex(random_bytes(16));echo $token;

This produces a 32-character hexadecimal string because each byte is represented by two hexadecimal characters.

Generate a Secure Random String of a Specific Length

If you need a secure alphanumeric string with a specific length, you can use random_int() to select characters from a predefined character set.

function secure_random_string($length = 32) {    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';    $charactersLength = strlen($characters);    $result = '';    for ($i = 0; $i < $length; $i++) {        $result .= $characters[random_int(0, $charactersLength - 1)];    }    return $result;}echo secure_random_string(32);

This approach is useful when you specifically need an alphanumeric output and want stronger randomness than older pseudo-random approaches.

Random String vs Unique String

A random string and a guaranteed unique string are not exactly the same thing.

A random generator selects characters based on randomness. There is always a theoretical possibility that the same value can be generated again.

If your application requires uniqueness, use an appropriate uniqueness strategy. For example, you can combine a random value with a database uniqueness constraint or use a UUID.

$id = bin2hex(random_bytes(16));echo $id;

The important distinction is that randomness reduces the probability of collisions, while a uniqueness constraint can enforce uniqueness at the database level.

Things to Consider When Generating Random Strings

Choose the Right Length

The longer the string and the larger the character set, the more possible combinations are available. Use a length appropriate for the application's purpose rather than generating unnecessarily short identifiers.

Consider the Character Set

If users need to manually type or communicate the generated value, avoid characters that can easily be confused, such as 0 and O, or 1 and I.

Do Not Use Random Strings as Passwords Without Proper Handling

If you are generating passwords for users, consider a dedicated password-generation and password-storage strategy. Passwords should be securely hashed using PHP's password hashing functions rather than stored as plain text.

Use Cryptographically Secure Randomness for Security Tokens

For authentication and security-sensitive applications, use PHP's cryptographically secure functions such as random_bytes() and random_int().

Frequently Asked Questions

How do I generate a random string in PHP?

You can generate a random string in PHP by creating a character set, selecting random characters, and combining them into a string. For security-sensitive values, PHP's random_bytes() or random_int() should be preferred.

How can I generate a 10-character random string in PHP?

Call the function with a length of 10:

echo generate_string(10);

If your function has a default length of 10, you can also simply call:

echo generate_string();

Can I generate a random string of any length?

Yes. A random string function can accept a length parameter, allowing you to generate strings of different sizes. When designing a secure generator, make sure the function validates the requested length and uses an appropriate source of randomness.

Are PHP random strings guaranteed to be unique?

No. Random strings are not automatically guaranteed to be unique. If uniqueness is important, use a database unique constraint or another identifier strategy and handle possible collisions.

What is the best way to generate a secure random string in PHP?

For security-sensitive applications, PHP's random_bytes() is a strong choice for generating cryptographically secure random data. random_int() is also suitable when you need to select random characters from a defined character set.

What is the difference between random_bytes() and random_int()?

random_bytes() generates cryptographically secure random bytes, while random_int() generates cryptographically secure random integers within a specified range. Both are useful for security-sensitive random values, depending on the format you need.

Can random strings be used for password reset links?

They can be used as tokens for password-reset workflows, but the token must be generated using a cryptographically secure method. Avoid using predictable random generators for authentication or password-reset tokens.

How long should a random token be?

The appropriate length depends on the application's security requirements and how the token is generated. For security-sensitive tokens, use a cryptographically secure random source and an adequately large token space rather than relying only on a short alphanumeric value.

Conclusion

A PHP random string generator is useful for creating identifiers, reference codes, temporary values, and other application data. The simple function shown above is suitable for basic use cases, while security-sensitive applications should use PHP's cryptographically secure random_bytes() and random_int() functions.

Before implementing a random string generator, consider whether you actually need randomness, uniqueness, or security. Choosing the right approach for the specific use case will make your PHP application more reliable and secure.

Need Help With PHP or Web Development?

Building a PHP application and need help with custom development, API integrations, performance improvements, automation, or application maintenance?

Contact SCRIPTBAKER to discuss your web development requirements and find the right solution for your project.