View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

How to Generate a Random String in PHP: 8 Ways with Examples

By Rohan Vats

Updated on Feb 13, 2025 | 16 min read | 1.8k views

Share:

A weak token like 123abc is easily guessable and vulnerable to brute-force attacks, while a strong, randomly generated token like b1F8@9G7k1z*8Q4! offers much higher security. This drastically reduces the risk of session hijacking and unauthorized access to sensitive data.

Generating random strings in PHP helps ensure secure session tokens and protect user privacy. With libraries like random_int and bin2hex, PHP is highly preferred by developers for developing secure, unpredictable strings.  

This blog covers 8 simple ways to generate random string in PHP, offering clear examples to help you implement them effectively in your projects.

How to Generate a Random String in PHP? 8 Simple Methods

PHP provides several built-in functions that allow developers to easily generate random, alphanumeric, and unique strings. These methods ensure that the generated strings are unpredictable, contributing to better security in web applications.

Here are some practical use cases of PHP strings:

Password Generation: Create secure and complex passwords for users.

Session Tokens: Generate unique strings for session identification to prevent session hijacking.

Data Anonymization: Replace sensitive data with random strings while maintaining data integrity.

PHP provides two types of random string generation methods:

Cryptographic Methods: Functions like random_int() and random_bytes() are secure and unpredictable, suitable for sensitive tasks like password generation or security tokens.

Non-Cryptographic Methods: Functions like rand() and mt_rand() are faster but use predictable algorithms, making them less secure for tasks that require strong randomness, such as generating secure passwords.

Now, let's explore how to generate random strings using these methods.

If you want to know how to generate a random string in php, let’s explore these eight simple methods of string generation:

1. Using random_int()

The random_int() function generates cryptographically secure random integers, making it a highly secure choice for generating random strings, especially in sensitive applications like passwords or session tokens. 

This method to generate random string in PHP is preferred over methods like rand() because it ensures better randomness and is resistant to predictability. However, its primary limitation is that it’s only capable of generating numbers and requires further processing to convert them into strings.

Code:

<?php
$n = 12; // Set the length of the random string to 12

function getRandomString($n) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // Define the character set (digits + lowercase + uppercase letters)
    $randomString = ''; // Initialize an empty string to store the result

    // Loop through to generate each character of the string
    for ($i = 0; $i < $n; $i++) {
        $index = random_int(0, strlen($characters) - 1); // Randomly select an index from the character set
        $randomString .= $characters[$index]; // Append the character to the string
    }

    return $randomString; // Return the generated random string
}

echo getRandomString($n); // Call the function and print the result
?>

Explanation: This PHP code generates a random string of length 12, using digits (0-9), lowercase (a-z), and uppercase (A-Z) characters.

$n = 12: Sets the desired length of the random string.

$characters: Contains the characters to choose from (digits + letters).

random_int(): Securely generates a random index to select characters from the $characters string.

Loop: Repeats the process 12 times, appending random characters to form the string.

Sample Output:

J3b9Lx7zT0kV

The output string will vary each time the script runs.

Why It's Better:

Cryptographically secure

Best for sensitive data (e.g., passwords, tokens)

Limitations:

Limited to generating numbers, not characters directly

Real-World Example: For secure session token generation in web applications, random_int() is used to ensure that each session ID is unpredictable and resistant to attacks like session hijacking.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months
View Program

Job-Linked Program

Bootcamp36 Weeks
View Program

You can also enhance your understanding of PHP string manipulation and other core programming techniques with upGrad’s online software engineering courses. They provide hands-on experience in implementing efficient PHP methods for real-world applications.

Also Read: String to Array in PHP: List of Functions Used

2. Using rand()

rand() is one of the simplest ways to generate random numbers in PHP. It can be used to generate random strings by selecting characters from a set, making it a good choice for non-sensitive applications where high security is not a concern. 

However, it’s not cryptographically secure and should be avoided for sensitive data. While mt_rand() offers better randomness and performance than rand(), both are non-cryptographic and should be avoided for sensitive data or security-related tasks. 

mt_rand() is suitable for general-purpose random number generation where security isn't a concern. But, for cryptographically secure operations, you should use functions like random_int(), openssl_random_pseudo_bytes(), or sodium_crypto_generichash().

Code:

<?php
$n = 12; // Set the length of the random string to 12

function getRandomString($n) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // Define the character set (digits + lowercase + uppercase letters)
    $randomString = ''; // Initialize an empty string to store the result

    // Loop through to generate each character of the string
    for ($i = 0; $i < $n; $i++) {
        $index = rand(0, strlen($characters) - 1); // Randomly select an index from the character set using rand()
        $randomString .= $characters[$index]; // Append the character to the string
    }

    return $randomString; // Return the generated random string
}

echo getRandomString($n); // Call the function and print the result
?>

Explanation: rand(0, strlen($characters) - 1): The function generates a random integer within the range of 0 to one less than the length of the $characters string. This value is then used to pick a random character from the string.

Sample Output:

sX1p6LmE9hJh

This string will be randomly generated, using digits and both uppercase and lowercase letters.

Why It's Better:

Simple to implement and understand

Suitable for non-secure applications like random sample generation

Limitations:

Not secure for cryptographic purposes

Lower randomness compared to methods like random_int()

Real-World Example: In a game where random loot or rewards are distributed, rand() can be used to randomly assign rewards from a predefined list of items.

Also Read: A Complete Guide to Implode in PHP: Syntax, Parameters, Examples, and More

3. Using String Shuffling to Generate a Random Substring

Using str_shuffle() is an easy and efficient way to generate random strings by shuffling a set of characters. It works well when you want a random permutation of characters without specific constraints. 

If you use this method to generate random string in PHP, it will allow you to shuffle a string and extract a random substring. This makes it great for non-sensitive tasks like generating temporary identifiers or tokens. However, str_shuffle() may not offer sufficient security for critical applications like password generation.

Code:

<?php
$n = 12; // Set the length of the random substring
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // Define the character set (digits + lowercase + uppercase letters)

function getRandomShuffledSubstring($n, $characters) {
    // Shuffle the string to randomize the order of characters
    $shuffledString = str_shuffle($characters);
    
    // Return a substring of the shuffled string with length $n
    return substr($shuffledString, 0, $n);
}

echo getRandomShuffledSubstring($n, $characters); // Call the function and print the result
?>

Explanation:

str_shuffle($characters): This function shuffles the string $characters to create a random order of its characters.

substr($shuffledString, 0, $n): After shuffling, the substr() function extracts the first $n characters from the shuffled string.

Sample Output:

Aw3zDp0XjL6q

This output is a randomly shuffled string, and then a substring of length 12 is taken from it. Each run produces a different result due to the shuffle.

Why It's Better:

Quick and simple to implement

Generates unique random substrings from a given character set

Limitations:

Not suitable for cryptographic security

May produce patterns in predictable shuffles

Real-World Example: For CAPTCHA generation, where random characters need to be shown to users for verification, str_shuffle() can be used to randomly shuffle a set of characters to create a distorted string.

Also Read: Basename in PHP | PHP basename() Function

4. Using bin2hex()

bin2hex() converts binary data into a hexadecimal representation, often used for generating unique and cryptographically secure strings. It is great for generating random tokens or identifiers for applications that require a high level of security. 

The random_bytes() function provides cryptographically secure random data, making it much safer than rand() or mt_rand(). Its downside is that the result is a long hexadecimal string, which might not always be the ideal format for certain use cases.

Code:

<?php
$n = 12; // Set the length of the random substring

function getRandomHexSubstring($n) {
    // Generate random binary data of length $n / 2 (since each byte is converted to two hex characters)
    $randomBinary = random_bytes($n / 2); 
    
    // Convert the binary data to hexadecimal
    $hexString = bin2hex($randomBinary);
    
    // Return a substring of the hexadecimal string with length $n
    return substr($hexString, 0, $n);
}

echo getRandomHexSubstring($n); // Call the function and print the result
?>

Explanation:

random_bytes($n / 2): Generates cryptographically secure random binary data. Since each byte corresponds to two hex characters, we request half the length of the desired string ($n / 2).

bin2hex($randomBinary): Converts the binary data into a hexadecimal string.

substr($hexString, 0, $n): Extracts the first $n characters from the hexadecimal string to generate the random substring.

Sample Output:

7f3a9c2b8d4e

This output is a random string generated from hexadecimal characters.

Why It's Better:

Cryptographically secure

Produces hexadecimal output, ideal for secure identifiers or tokens

Limitations:

Hexadecimal format may not be suitable for all applications

Not human-readable for casual use

Real-World Example: For generating unique file names in a cloud storage application, bin2hex(random_bytes()) ensures that file names are both unique and secure, reducing the risk of collisions.

Also Read: OOPS Concepts in PHP | Object Oriented Programming in PHP

5. Using mt_rand()

mt_rand() is a faster alternative to rand(), based on the Mersenne Twister algorithm. It is more efficient than rand() for generating random numbers, making it ideal for tasks that don’t require cryptographic security but need good performance. 

This method to generate random string in PHP is particularly useful for non-sensitive random strings, such as generating sample data or game identifiers. However, like rand(), it’s not suitable for security-sensitive applications.

Code:

<?php
$n = 12; // Set the length of the random string
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // Define the character set (digits + lowercase + uppercase letters)

function getRandomStringWithMtRand($n, $characters) {
    $randomString = ''; // Initialize an empty string to store the result

    // Loop through to generate each character of the string
    for ($i = 0; $i < $n; $i++) {
        $index = mt_rand(0, strlen($characters) - 1); // Randomly select an index from the character set using mt_rand()
        $randomString .= $characters[$index]; // Append the character to the string
    }

    return $randomString; // Return the generated random string
}

echo getRandomStringWithMtRand($n, $characters); // Call the function and print the result
?>

Explanation:

mt_rand(0, strlen($characters) - 1): This function generates a random integer between 0 and strlen($characters) - 1. It’s used to select a random index from the $characters string.

Loop: The loop runs $n times (12 in this case), and in each iteration, a random character is appended to the $randomString.

Sample Output:

b9Xl5p3VmK0Z

This string consists of random digits and letters (both uppercase and lowercase), and each time you run the script, the output will change due to the randomness of mt_rand().

Why It's Better:

Faster than rand() for larger datasets

Suitable for non-sensitive, high-performance applications

Limitations:

Not cryptographically secure

Not ideal for security-critical applications like password generation

Real-World Example: For randomly selecting a user for a survey or raffle, mt_rand() can be used due to its speed and efficiency when generating random numbers within a large dataset.

Also Read: SQL String Functions: Overview

6. Using Hashing sha1()

sha1() generates a 40-character hash from a given string and is widely used for generating unique identifiers or fingerprints. It’s beneficial when you need a consistent, reproducible random string derived from input data, such as generating unique file names. 

However, sha1() is considered weak in cryptography and is no longer recommended for password hashing or sensitive data. It is suitable for non-secure applications that require hash-based string generation.

Code:

<?php
$n = 12; // Set the length of the random substring

function getRandomStringWithSha1($n) {
    // Generate a random hash by hashing some random data (e.g., current time and a random number)
    $randomHash = sha1(mt_rand() . microtime());
    
    // Return a substring of the hash with length $n
    return substr($randomHash, 0, $n);
}

echo getRandomStringWithSha1($n); // Call the function and print the result
?>

Explanation:

sha1(mt_rand() . microtime()): This generates a hash based on the combination of a random number (mt_rand()) and the current time in microseconds (microtime()). Since sha1() produces a 40-character hexadecimal string, this approach ensures that the hash will be different each time.

substr($randomHash, 0, $n): This takes the first $n characters of the hash (in this case, 12 characters).

Sample Output:

fb0bfa2a8b6f

This output is a random string generated from the first 12 characters of a sha1() hash. You can adjust the length $n to get a longer or shorter substring of the hash.

Why It's Better:

Ideal for generating unique, reproducible hashes

Used for checksums and data integrity verification

Limitations:

Not secure for passwords or cryptographic uses

Not ideal for highly sensitive data

Real-World Example: When creating unique identifiers for transactions or records in a database, sha1() can be used to generate a consistent and unique hash, ensuring that each entry can be reliably referenced.

Also Read: 14 Best PHP Project Ideas & Topics For Beginners

7. Using Hashing md5()

md5() creates a 32-character hash, similar to sha1(), and is commonly used for generating unique identifiers or checksums. Although faster than sha1(), it is also considered cryptographically broken and unsuitable for security applications like password storage. 

Using this method to generate random strings in PHP is a good choice when you need a quick, consistent hash for non-sensitive applications, like file integrity checks or generating simple identifiers.

However, md5() is considered broken and vulnerable to collision attacks, where two different inputs can produce the same hash. It should never be used for cryptographic security purposes.

Code:

<?php
$n = 12; // Set the length of the random substring

function getRandomStringWithMd5($n) {
    // Generate a random hash by hashing some random data (e.g., current time and a random number)
    $randomHash = md5(mt_rand() . microtime());
    
    // Return a substring of the hash with length $n
    return substr($randomHash, 0, $n);
}

echo getRandomStringWithMd5($n); // Call the function and print the result
?>

Explanation:

md5(mt_rand() . microtime()): This combines a random number (mt_rand()) with the current timestamp (microtime()) and hashes the combined string using md5(). The result is always a unique 32-character hexadecimal string.

substr($randomHash, 0, $n): This takes the first $n characters (12 in this case) from the 32-character md5() hash to form the random string.

Sample Output:

f47c3a6b7d5e

This output is a random 12-character string derived from the md5() hash. You can adjust the length $n to extract a longer or shorter substring.

Why It's Better:

Fast and efficient for quick hash generation

Ideal for simple identifiers and file verification

Limitations:

Not secure for passwords or sensitive information

Insecure for cryptographic purposes (vulnerable to collisions)

Real-World Example: For data integrity checks, md5() can be used to generate a hash of a file before and after transfer to ensure that the file has not been tampered with or corrupted during transmission.

Also Read: PHP Array Length: A Complete Guide to Finding Array Length in PHP [With Examples]

8. Using PHP uniqid()

The uniqid() function generates a unique identifier based on the current time in microseconds. This method is especially useful when you need to generate unique IDs for session tokens, temporary file names, or database keys. 

It's simple and ensures that each generated string is unique, but it is predictable and therefore not secure for generating random tokens in cryptographic contexts.

However, while uniqid() generates unique identifiers based on the system clock, it is predictable because it relies on the current time. This predictability makes it unsuitable for security-sensitive tasks, such as generating session tokens or cryptographic IDs.

Code:

<?php
$n = 12; // Set the length of the random substring

function getRandomStringWithUniqid($n) {
    // Generate a unique ID
    $uniqueId = uniqid('', true); 
    
    // Return a substring of the unique ID with length $n
    return substr($uniqueId, 0, $n);
}

echo getRandomStringWithUniqid($n); // Call the function and print the result
?>

Explanation:

uniqid('', true): Generates a unique ID based on the current time in microseconds. The true parameter adds more entropy by including a more precise timestamp.

substr($uniqueId, 0, $n): Extracts the first $n characters from the unique ID string. In this case, it extracts the first 12 characters.

Sample Output:

605b97d7f51c

This is a random 12-character substring of the unique ID generated by uniqid(). You can change $n to get a longer or shorter substring, depending on your needs.

Why It's Better:

Generates quick, unique IDs based on microtime

Ideal for temporary file names, session IDs, or unique records

Limitations:

Predictable for attackers

Not suitable for cryptographic tokens or secure passwords

Real-World Example: For generating unique order IDs in an e-commerce platform, uniqid() can be used to create an ID based on the current time, ensuring that each order has a distinct identifier.

These methods offer a variety of approaches to generate random string in PHP, each tailored to different use cases, from secure password generation to simple identifier creation. 

For cryptographically secure random data, PHP provides openssl_random_pseudo_bytes() and sodium_crypto_generichash(). These functions are designed for secure, unpredictable random number generation and are recommended for tasks like password hashing, token generation, and other security-related applications.

Understanding their strengths and limitations allows you to choose the right method for your specific needs.

Also Read: How to Convert Object to Array in PHP

Now that you’ve learned how to generate a random string in PHP, let’s explore the benefits and challenges these techniques present, so you can choose the right approach for your needs.

Benefits and Drawbacks of Generating a Random PHP String

Generating random strings in PHP is a crucial task in many web development projects. From creating secure passwords to generating session tokens and unique identifiers, random strings ensure data privacy and enhance application security. 

The flexibility of PHP's random string generation methods makes them ideal for a variety of use cases across industries, such as e-commerce, banking, social media, and more.

Below is a combined table outlining the benefits and drawbacks of generating random strings in PHP:

Aspect

Benefits

Drawbacks

Security Ensures unpredictable passwords and tokens for stronger security. rand() and mt_rand() are predictable in cryptographic contexts.
Data Anonymization Used to replace sensitive data, improving privacy. Methods like rand() are not suitable for secure data anonymization.
Unique Identifiers Creates collision-free IDs for sessions and files. uniqid() may produce shorter strings, limiting flexibility.
Prevents Predictability Ensures randomness in token generation for security. Some methods, like mt_rand(), are not secure for sensitive applications.
Versatility Useful for tasks like URL shortening and tracking IDs. Some methods like random_int() are slower for high-volume tasks.
Performance Fast methods like rand() are ideal for simple applications. random_int() and random_bytes() are slower for larger or frequent generation.
Memory Usage Efficient for small random strings. Large random strings may cause higher memory usage and performance issues.

Also Read: Must Read 10 PHP Interview Questions and Answers For Beginners & Experienced

Understanding the advantages and limitations will help you make better decisions. upGrad can further assist you in mastering PHP string manipulation through in-depth, hands-on learning.

How Can upGrad Assist You in Excelling PHP Strings?

upGrad, South Asia's leading EdTech platform with 10M+ learners, offers expert-led PHP courses. These courses cover essential string handling techniques and practical implementations, helping you master PHP and apply it in real-world projects.

Here are some relevant courses you can check out:

AI-Powered Full Stack Development Course by IIITB

Master’s Degree in Artificial Intelligence and Data Science

Master of Design in User Experience

Professional Certificate Program in UI/UX Design

Executive Diploma in Data Science & AI

You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today! 

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Frequently Asked Questions (FAQs)

1. What is the difference between rand() and random_int() in PHP?

2. Can I generate random strings with special characters in PHP?

3. Which PHP method should I use to generate secure session tokens?

4. Is there a PHP function to generate random strings of a specific length?

5. How can I generate a random string in PHP for use in a CAPTCHA system?

6. Is uniqid() suitable for generating secure passwords?

7. How do I make sure the random string is truly unique across different sessions?

8. Can I use PHP to generate random strings for database primary keys?

9. What’s the best way to generate a random string for a file name?

10. How do I generate random strings in PHP without including numbers?

11. How does str_shuffle() compare to random_int() for generating secure strings?

Rohan Vats

408 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

View Program
upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

View Program
upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

View Program