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.
PHP
<?php
$n = 10;
function getRandomString($n) {
return bin2hex(random_bytes($n / 2));
}
echo getRandomString($n);
?>
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.
PHP
<?php
function getRandomString() {
return uniqid();
}
echo getRandomString();
?>
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.
PHP
<?php
$n = 10;
function getRandomString($n) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $n; $i++) {
$index = random_int(0, strlen($characters) - 1);
$randomString .= $characters[$index];
}
return $randomString;
}
echo getRandomString($n);
?>