dimanche 21 mars 2021

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




Aucun commentaire:

Enregistrer un commentaire