Generating random strings in PHP has never been easier! With just a few lines of code, you can create a random string of characters that can be used in a variety of ways. Whether you need a unique identifier for a user’s profile or a secure password for a website, random strings can help. PHP’s random string function is incredibly straightforward to use. All you need to do is specify the length of the string and the character set you want to use. You can generate strings that include numbers, special characters, and even emoji. The possibilities are endless! With PHP’s random string function, you can quickly generate unique and secure strings for whatever purpose you need. So don’t wait – get started creating random strings today!
Method 1: Generate Random String with Custom function
This is a custom function to generate a random string of a defined length. Using this you can limit the characters, and symbols to be used in the random string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php function generateRandomString($length) { $include_chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; /* Uncomment below to include symbols */ /* $include_chars .= "[{(!@#$%^/&*_+;?\:)}]"; */ $charLength = strlen($include_chars); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $include_chars [rand(0, $charLength - 1)]; } return $randomString; } // Call function $lenght = 12; # Set result string lenght echo generateRandomString($lenght); ?> |
Output:
b55ABxtxikMX
Method 2: Generate Random String Using uniqid() function
The uniqid() function generate a Unique id based on the current time in microseconds. This function has a limitation, the result string has a fixed length of 13 characters.
1 2 3 4 | <?php $result = uniqid(); echo $result; ?> |
Output:
335cdb93bf5dddf
Method 3: Generate Random String Using random_bytes() function
The random_bytes() function generates a cryptographically secure pseudo-random byte of defined length. This result will be in binary format, which you can convert to a hex value using bin2hex() function.
1 2 3 4 5 | <?php $bytes = 10; $result = bin2hex(random_bytes($bytes)); echo $result; ?> |
Output:
ba3614e6ee7802b3428b
Conclusion
This tutorial helped you to generate random strings using PHP scripts. We have discussed 3 methods for generating random strings in PHP.