Lokomass
Lokomass

Reputation: 47

Generate secure random password in PHP

I've made a php function which generate random password. But, sometimes, password length is different that I want (I fixed it to 10) and I don't understand why ? I wish password don't start by special char if it possible. Can you help me please ?

<?php
    function get_random_password() {
        $digits = range('0', '9');
        $lowercase = range('a', 'z');
        $uppercase = range('A', 'Z'); 
        $special = str_split('!@#$%^&*+=-_?.,:;<>(){}[]/|~`\'"');
        shuffle($digits);
        shuffle($special);
        shuffle($lowercase);
        shuffle($uppercase);
        $array_special = array_rand($special);
        $array_digits = array_rand($digits, 3);
        $array_lowercase = array_rand($lowercase, 3);
        $array_uppercase = array_rand($uppercase, 3);
        $password = str_shuffle(
            $special[$array_special].
            $digits[$array_digits[0]].
            $digits[$array_digits[1]].
            $digits[$array_digits[2]].
            $lowercase[$array_lowercase[0]].
            $lowercase[$array_lowercase[1]].
            $lowercase[$array_lowercase[2]].
            $uppercase[$array_uppercase[0]].
            $uppercase[$array_uppercase[1]].
            $uppercase[$array_uppercase[2]]
        );
        if (strlen($password) > 10) {
            $password = substr($password, 0, 10);
        }
        return $password;
    }
    for ($i=0;$i<=30;$i++) {
        echo get_random_password()."<br>";
    }
?>

enter image description here

Upvotes: 1

Views: 1130

Answers (1)

Roman
Roman

Reputation: 2549

I ran your code several times. It always returns passwords which are 10 chars long.

I see the following problems:

  • you are printing it out in html, so chars like < and > can break your html code
  • also line breaks could be a problem

To solve this:

  • Do not print it out in browser, better test your function in a console.
  • If you want to print it out in html, then you have to use the htmlentities() (PHP documentation) function to display it correctly in the browser. Do not store the passwords with htmlentities() as this would replace the special characters in your passwords with the html entities.

Upvotes: 2

Related Questions