Often times you’ll come across the need to generate a random string. When you search for something like “PHP random string function” which will probably just be cut & pasted into your code, you’ll typically find something like this function:

function genRandomString($length = 10) {
    $characters = ‘0123456789abcdefghijklmnopqrstuvwxyz’;
    $string = ”;
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];

    return $string;

While that’s great and all, don’t you just feel like there’s some better, simpler way to generate a random string? Preferably something done all in one line, so you don’t even need a function inside your code?

There is a way. Actually, there are lots of ways. There are numerous functions in PHP that can be used to generate a string of random characters, and the one I typically use here is something you’ve probably used quite a bit… md5().

If you aren’t familiar with it, MD5 is a commonly used hashing technique that can be used to generate a unique 32-character “fingerprint” of a string. While it has been shown to have some security holes and not be collision proof, that isn’t really a concern the majority of the time you need to generate a random string. So, we’ll go ahead and use it here.

echo MD5(); // PHP Warning:  md5() expects at least 1 parameter, 0 given 

So, we need to pass in something, anything, but try to be unique. microtime() is a good choice.

echo MD5(microtime()); // 5959e4c551ee3a91d89449437b681ead

Great, now we have a random 32 character string. But what if you only want a slice of that, like 5 characters? substr() is your answer.

echo substr(MD5(microtime(), 0, 5); // 5959e

If you are concerned about security and making this string even more random, just shuffle it with str_shuffle().

echo substr(str_shuffle(MD5(microtime())), 0, 5); // 6c468

Now wasn’t that easy?