PHP Simple Random String Generator
Here is a simple function for generating a random string via PHP. Oh I can hear it now, all the “random-things” experts out there crying out in pain because the function doesn’t return actual true random numbers. And they are right, true “randomness” is difficult to measure and achieve, especially with PHP. So for this post, “random” means quasi-random or pseudo-random. I.e., random enough for casual functionality.
That in mind, if you need 100% truly pure random strings for some top-secret encrypted security system whatever, go look elsewhere. But if you’re like me and just need a “random” alphanumeric string for things like determining order, assigning usernames, and generating passwords, then welcome. The following function is well-suited to spit out strings that are plenty random for most casual purposes.
Simple way to generate a random string
Here is the most basic, simplest way that I’ve found to output a random string. It’s a function containing two lines of code, and works great.
function wpmix_get_random_string($length) {
$string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
return substr(str_shuffle($string), 0, $length);
}
As written, this simple function will output a case-insensitive alphanumeric string. For example, when called as a variable named $random_string
:
$random_string = wpmix_get_random_string(10);
That will return some random string that is 10
characters in length, like hsa8h3JsW1
. You can change the $length
argument to whatever is required. And also can customize the characters that may be used in generating the string. For example, if you want to output only numeric strings, you would change the $string
variable like so:
$string = '0123456789';
Or to output only lowercase alphabetical characters:
$string = 'abcdefghijklmnopqrstuvwxyz';
And so forth and so on.