我有一个类来登录用户,但是当我使用表单和错误的凭据对其进行测试时,我仍然获得了“成功”。有人能指出我正确的方向吗?
include('User.datatype.php');
$usher = new Authenticator;
$usher->checkCreds();
$usher->ensureHasAccess();
Class Authenticator {
protected $user;
protected function getCreds() {
if (!isset($_POST['login']))
throw new Exception("There was an error processing your request", 1);
else if ($_POST['username'] == '' || $_POST['password'] == '')
throw new Exception("You must enter a username and password", 1);
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$this->user = new User;
$this->user->username = $username;
$this->user->password = $password;
}
public function checkCreds() {
$this->getCreds();
if (empty($this->user->username) || empty($this->user->password))
throw new Exception("Error Processing Request", 1);
include('dbconnect.php'); // Normally I'd store the db connect script outside of webroot
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare('SELECT * FROM Users WHERE username = :uname AND password = :pword');
$stmt->bindParam(':uname', $this->user->username);
$stmt->bindParam(':pword', $this->user->password);
$stmt->execute();
$status = $stmt->fetch();
$this->user->status = $status;
print $status;
return $this->user->status;
}
protected function createSessionID() {
$seshID = mt_rand(99999, 1000000);
return $seshID;
}
protected function startSession() {
if (empty($this->user->status))
throw new Exception("There was a problem connecting to the database", 1);
session_start();
$_SESSION['username'] = $this->user->username;
$_SESSION['id'] = createSessionID();
$secret = $_SESSION['id'];
header('Location:index.php?' . $secret);
return true;
}
protected function hasAccess() {
$this->startSession();
if (!startSession())
throw new Exception("You do not have access to this page.", 1);
return true;
}
public function ensureHasAccess() {
if(!$this->hasAccess())
throw new Exception("You are not logged in.");
print 'Welcome, ' . $this->user->username;
}
}
HTML 表单:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
</head>
<body>
<form action="authenticator.php" method="post">
<p>username: <input type="text" name="username" /></p>
<p>password: <input type="password" name="password" /></p>
<p><input type="submit" name="login" /></p>
</form>
</body>
</html>