<?php
class Login
{
private $dbh = null;
private $dsn ,$host, $username , $password= null;
public $errors = array();
public $messages = array();
public function __construct()
{
session_start();
require_once 'dbconfig.php';
if (isset($_GET["logout"])) {
$this->doLogout();
}
elseif (isset($_POST["login"])) {
$this->dologinWithPostData();
}
}
private function dologinWithPostData()
{
if (empty($_POST['user_name'])) {
$this->errors[] = "Username field was empty.";
}
elseif (empty($_POST['user_password'])) {
$this->errors[] = "Password field was empty.";
}
elseif (!empty($_POST['user_name']) && !empty($_POST['user_password'])) {
$this->$dsn = "mysql:host=$host;dbname=$dbname"; // $dbname is empdb as in dbconfig.php
$this->$dbh = new PDO($dsn, $username, $password);
$this->$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!$this->dbh->set_charset("utf8")) {
$this->errors[] = $this->dbh->error;
}
if (!$this->dbh->connect_errno) {
$user_name = $this->dbh->real_escape_string($_POST['user_name']);
$sql = "SELECT user_name, user_email, user_password_hash
FROM users
WHERE user_name = '" . $user_name . "' OR user_email = '" . $user_name . "';";
$result_of_login_check = $this->db_connection->query($sql);
if ($result_of_login_check->num_rows == 1) {
$result_row = $result_of_login_check->fetch_object();
if (password_verify($_POST['user_password'], $result_row->user_password_hash)) {
$_SESSION['user_name'] = $result_row->user_name;
$_SESSION['user_email'] = $result_row->user_email;
$_SESSION['user_login_status'] = 1;
}
else {
$this->errors[] = "Wrong password. Try again.";
}
}
else {
$this->errors[] = "This user does not exist.";
}
}
else {
$this->errors[] = "Database connection problem.";
}
}
}
public function doLogout()
{
$_SESSION = array();
session_destroy();
$this->messages[] = "You have been logged out.";
}
public function isUserLoggedIn()
{
if (isset($_SESSION['user_login_status']) AND $_SESSION['user_login_status'] == 1) {
return true;
}
// default return
return false;
}
我一直在尝试使用php中的会话创建一个php登录页面。但是在我输入登录页面的值后,我得到的错误如下:
Undefined variable: host in www\proj\Login.php on line 38
Undefined variable: dbname in \www\proj\Login.php on line 38
Undefined variable: dsn in \www\proj\Login.php on line 38
Cannot access empty property in \www\proj\Login.php on line 38
是导致问题的查询还是我错误地包含了db.config。我已经包含 dbconfig.php 文件,该文件已初始化所有这些变量。