3

I'm trying to create a random string with numbers and letters and I found this function and thought it would be good, but I don't know if it is the correct way to create a true random string or if there is an easier way to do this? Below is what I have:

function randomGen() {
    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $length = strlen($chars);
    $random;

    for ($i = 0; $i < 8; $i++) {
        $random = $chars[rand(0, $length - 1)];
    }

    return $random;
}

1 Answers1

5

You could try using $random = substr(str_shuffle(MD5(microtime())), 0, 8);, which will output the same amount of random characters as you have in your example. I actually prefer this method over most as it doesn't require you to put in the expected characters and even more importantly, it can be done in one line of code!

NightOwlPrgmr
  • 1,322
  • 3
  • 21
  • 31