VOOZH about

URL: https://www.geeksforgeeks.org/php/generating-random-string-using-php/

⇱ Generating Random String Using PHP - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generating Random String Using PHP

Last Updated : 11 Jul, 2025

Generating a random string involves creating a sequence of characters where each character is selected unpredictably from a defined set (e.g., letters, numbers, symbols). This process is used in programming to produce unique identifiers, passwords, tokens, or keys for security and randomness in applications.

EA070
aBX32gTf

Using random_bytes() Function

The random_bytes() function generates cryptographically secure random bytes, which can be converted to a readable string format using functions like bin2hex(). This approach ensures high security, making it suitable for generating secure tokens, passwords, or unique identifiers.

Example: In this example we generates a random string of length 10 using the random_bytes() function, converts it to hexadecimal using bin2hex(), and then outputs the random string.


Output
b1ff0733db

Using uniqid() Function

The uniqid() function generates a unique string based on the current time in microseconds, optionally adding more entropy for uniqueness. It’s not cryptographically secure but useful for generating unique identifiers quickly in non-critical scenarios like naming files or sessions.

Example: In this example we generates a unique random string using the uniqid() function, which creates a unique identifier based on the current timestamp, ensuring uniqueness across different executions.


Output
66e261e8bd5ba

Using random_int() Function in a Custom Function

The random_int() function generates cryptographically secure random integers, which can be used to select characters from a predefined set in a loop. This approach ensures secure and random string generation, ideal for passwords, tokens, or secure identifiers.

Example : In this example we generates a random string of length 10 by selecting characters from a predefined set of digits, lowercase, and uppercase letters, using the random_int() function for secure random indexing.


Output
Qc8RnOI22X
Comment
Article Tags:
Article Tags: