PHP generates the implementation code for the random username and password

  • 2020-05-27 04:39:58
  • OfStack

Sometimes we need to use in your application randomly generated username and password, it can greatly improve the security of the application, generate random in PHP user name and password can use mt_rand function or rand function, rand function in the application of authentication code 1 more, and growth characters of random code 1 need mt_rand function.

Using PHP to generate random Numbers can be used in many places, such as designing a program's random password, an application that simulates a dice game, a rock and paper game application, and so on.

The following are the two function methods of PHP to generate random Numbers:


// Automatically randomly generate user names for users ( The length of the 6-13) 
        function create_password($pw_length = 4){
            $randpwd = '';
            for ($i = 0; $i < $pw_length; $i++){
                $randpwd .= chr(mt_rand(33, 126));
            }
            return $randpwd;
        }
        function generate_username( $length = 6 ) {
            //  Password character set, you can add any character you want  
            $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
            $password = '';
            for ( $i = 0; $i < $length; $i++ )
            {
                //  There are two ways to get characters 
                //  The first 1 Is using substr  The interception $chars Any of the 1 A character; 
                //  The first 2 You take an array of characters $chars  Any element of 
                // $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
                $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
            }
            return $password;
        }
        //  Call this function  
        $userId = 'user'.generate_username(6);
        $pwd = create_password(9);


Related articles: