A php user name and password verification instance program. For more information, see.
The user name and password entered by the user are verified during logon.
| The Code is as follows: |
Copy code |
|
<? Php
/**
* Validator for Login.
*/
Final class LoginValidator {
Private function _ construct (){
}
/**
* Validate the given username and password.
* @ Param $ username and $ password to be validated
* @ Return array of {@ link Error} s
*/
Public static function validate ($ username, $ password ){
$ Errors = array ();
$ Username = trim ($ username );
If (! $ Username ){
$ Errors [] = new Error ('username', 'user name cannot be blank. ');
} Elseif (strlen ($ username) <3 ){
$ Errors [] = new Error ('username', 'user Name Length cannot be less than 3 characters. ');
} Elseif (strlen ($ username)> 30 ){
$ Errors [] = new Error ('username', 'the username length cannot exceed 30 characters. ');
} Elseif (! Preg_match ('/^ [A-Za-z] + $/', substr ($ username, 0, 1 ))){
$ Errors [] = new Error ('username', 'the user name must start with a letter. ');
} Elseif (! Preg_match ('/^ [A-Za-z0-9 _] + $/', $ username )){
$ Errors [] = new Error ('username', 'user name can only be a combination of letters, numbers, and underscores. ');
} Elseif (! Trim ($ password )){
$ Errors [] = new Error ('Password', 'the password cannot be blank. ');
} 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', 'the user name or password is incorrect. ');
}
} Else {
$ Errors [] = new Error ('username', 'user name does not exist. ');
}
}
Return $ errors;
}
}
?> |
2. Call the validators for verification.
| 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, 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 (). "<br> ";
} |