Developer Tools for Random Data Generation // v2.5.1
root@generate-random:~/strings/php$ _

Generate Random Strings in PHP

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: PHP

What: Generate random strings in PHP using <code>random_bytes()</code> for cryptographically secure random data. Perfect for tokens, IDs, and secure string generation.

Try it: Use our interactive Strings generator or integrate this code into your PHP application.

Generate random strings in PHP using random_bytes() for cryptographically secure random data. Perfect for tokens, IDs, and secure string generation. Looking for other languages? Check our code examples in JavaScript , Python , Java , C# , C++ , Ruby and Go or use our interactive web generator.

PHP Code Example

<?php
// Generate a random alphanumeric string
function generateRandomString($length = 16, $customChars = null) {
    if ($customChars !== null) {
        // Use custom character set
        $chars = $customChars;
        $result = '';
        $charsLength = strlen($chars);

        for ($i = 0; $i < $length; $i++) {
            $randomIndex = random_int(0, $charsLength - 1);
            $result .= $chars[$randomIndex];
        }

        return $result;
    }

    // Default: generate hex string from random bytes
    $bytes = random_bytes(ceil($length / 2));
    return substr(bin2hex($bytes), 0, $length);
}

// Generate a 16-character hex string
$hexString = generateRandomString(16);
echo $hexString;  // Example: a3f7b2e9c4d1f8a6

// Generate a 12-character alphanumeric string
$alphanumeric = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$customString = generateRandomString(12, $alphanumeric);
echo $customString;  // Example: aB3xY7mN2pQ9

[EXPLANATION]

This function uses random_bytes() to generate cryptographically secure random data. When no custom character set is provided, it uses bin2hex() for efficient hex string generation. For custom character sets, it uses random_int() for secure index selection.

Expected Output

a3f7b2e9c4d1f8a6
aB3xY7mN2pQ9

Common Use Cases

  • Session token and ID generation
  • API key and secret generation
  • Database primary keys (non-sequential)
  • File upload unique naming
  • Cache key generation
  • CSRF token generation

Important Notes

  • Use random_bytes() for cryptographic security
  • bin2hex() doubles the byte length (2 hex chars per byte)
  • Avoid rand() or mt_rand() for security tokens
  • Consider base64 encoding for URL-safe strings

Try Our Interactive Generator

Don't want to write code? Use our free web-based Strings generator with instant results.

TRY STRINGS GENERATOR →