A PHP login user name and password Authentication instance program, there are friends who need to learn to reference.
, authentication of user name and password entered by user at login
| The code is as follows |
Copy Code |
/** * Validator for Login. */ Final class Loginvalidator { Private Function __construct () {
} /** * Validate the given username and password. * @param $username and $password to be validated * @return Array array of {@link Error} s */ public static function Validate ($username, $password) { $errors = Array (); $username = Trim ($username); if (! $username) { $errors [] = new Error (' username ', ' username cannot be empty. '); } elseif (Strlen ($username) <3) { $errors [] = new Error (' username ', ' username cannot be less than 3 characters long. '); } elseif (Strlen ($username) >30) { $errors [] = new Error (' username ', ' username cannot be longer than 30 characters. '); } elseif (!preg_match ('/^[a-za-z]+$/', substr ($username, 0, 1))) { $errors [] = new Error (' username ', ' username must start with a letter. '); } elseif (!preg_match ('/^[a-za-z0-9_]+$/', $username)) { $errors [] = new Error (' username ', ' username can only be a combination of letters, numbers, and underscores (_). '); } elseif (!trim ($password)) { $errors [] = new Error (' Password ', ' password cannot be empty. '); } else { Check whether use exists or not $dao = new Userdao (); $user = $dao->findbyname ($username); if ($user) { if (! ( $user->getpassword () = = SHA1 ($user->getsalt (). $password))) { $errors [] = new error (' Password ', ' username or password is wrong. '); } } else { $errors [] = new Error (' username ', ' username does not exist. '); } } return $errors; } } ?> |
2. Call Authenticator for validation
| The code is as follows |
Copy Code |
$username = null; $password = null;
$msg = ""; if (isset ($_post[' username ')) && isset ($_post[' password ']) { $username = Addslashes (Trim (stripslashes ($_post [' username '))); $password = Addslashes (Trim (stripslashes ($_post [' Password '))); Validate $errors = Loginvalidator::validate ($username, $password);
if (empty ($errors)) { Save the latest IP or login time into database and then processing page forwarding $dao = new Userdao (); $user = $dao->findbyname ($username); $last _login_ip = utils::getipaddress (); $user->setlastloginip ($last _login_ip); $now = new DateTime (); $user->setlastlogintime ($now); $dao->save ($user); Userlogin::setuserinfo ($user); Flash::addflash (' Login successful! '); Utils::redirect (' welcome '); }
foreach ($errors as $e) { $msg. = $e->getmessage (). " "; } |
http://www.bkjia.com/PHPjc/633096.html www.bkjia.com true http://www.bkjia.com/PHPjc/633096.html techarticle a PHP login user name and password Authentication instance program, there are friends who need to learn to reference. , login to the user entered the user name, password to verify the code as follows copy Generation ...