DEV Community

ライフポータル
ライフポータル

Posted on • Originally published at code-izumi.com

PHP Random String Generation: Best Practices for Passwords, IDs, and Tokens

In web application development, you often need to generate random strings for various purposes:

  • "Generating temporary passwords for users."
  • "Creating unique, non-colliding filenames for uploads."
  • "Issuing secure CSRF tokens or API keys."

However, PHP offers several functions—rand, mt_rand, uniqid, random_bytes, and more. Choosing the wrong one can lead to security vulnerabilities. In this guide, we’ll break down the best methods for generating random strings based on security requirements and specific use cases.


1. Security First: Cryptographically Secure Strings

When handling sensitive data like passwords, session IDs, or tokens, you must use "cryptographically secure" methods. Standard functions like rand(), mt_rand(), or str_shuffle() are predictable and should never be used for security.

Recommended: random_bytes and bin2hex

Since PHP 7, random_bytes() has been the industry standard for generating unpredictable random data. To turn that data into a readable string, we typically use bin2hex().

<?php
// Generate 16 bytes of random data and convert to a 32-character hex string
$token = bin2hex(random_bytes(16));

echo "Generated Token: " . $token;
?>
Enter fullscreen mode Exit fullscreen mode

Output Example:
Generated Token: a3f9e2b1c8d7e6f5a4b3c2d1e0f9a8b7

Because each byte is represented by two hex characters, random_bytes(16) results in a 32-character string. This is the best practice for CSRF tokens and secure keys.


2. Generating Custom Alphanumeric Strings

If you need a string with a specific set of characters (e.g., uppercase, lowercase, and numbers for a password), the best way is to pick characters randomly using random_int().

Flexible and Secure Generator Function

<?php
/**
 * Generates a secure random string of a specified length.
 * @param int $length
 * @return string
 */
function generateRandomString($length = 10) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $max = strlen($chars) - 1;
    $result = '';

    for ($i = 0; $i < $length; $i++) {
        // random_int is cryptographically secure
        $index = random_int(0, $max);
        $result .= $chars[$index];
    }

    return $result;
}

// Generate a 12-character password
echo "Password: " . generateRandomString(12);
?>
Enter fullscreen mode Exit fullscreen mode

By using random_int(), this function remains secure enough for passwords while giving you full control over the character set.


3. Simple Strings for Non-Secure Use Cases

For scenarios where security isn't a priority—such as generating dummy test data or temporary non-sensitive filenames—you can use a quicker, more concise method.

Using str_shuffle

<?php
// Shuffle a string and take the first 8 characters
$randomStr = substr(str_shuffle('1234567890abcdefghijklmnopqrstuvwxyz'), 0, 8);

echo "Simple ID: " . $randomStr;
?>
Enter fullscreen mode Exit fullscreen mode

Note: This method is fast but predictable. Use it only for internal testing or UI elements where security doesn't matter.


4. Generating Unique IDs with uniqid

If your goal is to generate an identifier that is unlikely to collide (be duplicated), uniqid() is a specialized function that generates IDs based on the current time in microseconds.

Basic vs. High-Precision IDs

<?php
// Standard uniqid (13 characters)
echo "Standard: " . uniqid() . "\n";

// With a prefix
echo "With Prefix: " . uniqid("user_") . "\n";

// High-precision with more entropy (23 characters)
echo "High Precision: " . uniqid("", true) . "\n";
?>
Enter fullscreen mode Exit fullscreen mode

Pro Tip: For database primary keys or critical filenames, always set the second parameter to true. This adds additional entropy (randomness) at the end of the string, making collisions nearly impossible even if multiple IDs are generated at the exact same microsecond.


Conclusion

The right tool depends on your goal:

  1. For Tokens/Security: Use random_bytes().
  2. For Passwords: Use random_int() with a custom character loop.
  3. For Unique Filenames: Use uniqid('', true).
  4. For Mock Data: str_shuffle() is fine.

By choosing the correct function, you ensure your PHP applications are both functional and secure.


Originally published at: [https://code-izumi.com/php/random-string/]

Top comments (0)