一個php 登錄時用戶名與密碼驗證實例程序,有需要學習的朋友可參考參考。
、登錄時對用戶輸入的用戶名、密碼進行驗證
代碼如下 復制代碼
<?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 array of {@link Error} s
*/
public static function validate($username, $password) {
$errors = array();
$username = trim($username);
if (!$username) {
$errors[] = new Error('username', '用戶名不能為空。');
} elseif (strlen($username)<3) {
$errors[] = new Error('username', '用戶名長度不能小於3個字符。');
} elseif (strlen($username)>30) {
$errors[] = new Error('username', '用戶名長度不能超過30個字符。');
} elseif (!preg_match('/^[A-Za-z]+$/',substr($username, 0, 1))) {
$errors[] = new Error('username', '用戶名必須以字母開頭。');
} elseif (!preg_match('/^[A-Za-z0-9_]+$/', $username)) {
$errors[] = new Error('username', '用戶名只能是字母、數字以及下劃線( _ )的組合。');
} elseif (!trim($password)) {
$errors[] = new Error('password', '密碼不能為空。');
} 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', '用戶名或密碼錯誤。');
}
} else {
$errors[] = new Error('username', '用戶名不存在。');
}
}
return $errors;
}
}
?>
2、調用驗證器進行驗證
代碼如下 復制代碼
$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('登錄成功!');
Utils::redirect('welcome');
}
foreach ($errors as $e) {
$msg .= $e->getMessage()."<br>";
}