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;
}
7
  • What is wrong with the function ? Commented Jun 2, 2015 at 17:42
  • Nothing is wrong as far as syntax. I just am not sure if this is the best way. Seeing some of the other answers I can tell that I'm using more code than necessary. Commented Jun 2, 2015 at 17:43
  • use str_shuffle instead of writing separate function. Commented Jun 2, 2015 at 17:43
  • 1
    You should have a look on this project : github.com/fzaninotto/Faker Commented Jun 2, 2015 at 17:43
  • Sorry string random must be of laravel itself Commented Jun 2, 2015 at 17:43

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments