PHP&MySQLi OOP-为什么我的登录变量未设置为true?

山姆·莱恩

用户正确认证后,数据库类方法可以正常工作。会话是否设置为正确的用户ID,但未设置登录变量?Var dump返回false,但是在运行login方法之后应将其设置为true。

login.php

<?php 

//session is started in the initialize file and all required files are included
require_once('includes/init.php');

// set initial values so that input values using username and password variables do not return undefined as well as the error variable
$username = "";
$password = "";
$error = "";

if($session->isLoggedIn()) {
    redirect('index.php');
}

if (isset($_POST['submit'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);

    $foundUser = User::verify($username, $password);
    if ($foundUser) {
        $session->login($foundUser);
        redirect('index.php');
    } else {
        $error = "Combination incorrect";
    }
}

?>

session.php

<?php

// Session class allows to store session cookies so that data can be looked up without having to go back to the database
// Database objects not stored because they could get updated in the database so the cookies could become outdated

class Session {
    public $loggedIn = false;
    public $userId;

    function __contruct() {
        $this->checkLogin();
    }

    public function isLoggedIn() {
        return $this->loggedIn;
    }

    private function checkLogin() {
        if(isset($_SESSION['userId'])) {
            $this->userId = $_SESSION['userId'];
            $this->loggedIn = true;
        } else {
            unset($this->userId);
            $this->loggedIn = false;
        }
    }

    public function login($user) {
        if($user) {
            $this->userId = $_SESSION['userId'] = $user->userId;
            $this->loggedIn = true;
        }
    }

    public function logout() {
        unset($_SESSION['userId']);
        unset($this->userId);
        $this->loggedIn = false;
    }
}

$session = new Session();

?>

user.php

<?php

class User {

    public $userId;
    public $username;
    public $password;
    public $email;
    public $firstname;
    public $lastname;
    public $access;
    public $active;

    public static function getUsers() {
        return self::getBySQL("SELECT * FROM users");
    }

    public static function getUserId($id=0) {
        global $db;
        $resultArray = self::getBySQL("SELECT * FROM users WHERE userId={$id}");
        return !empty($resultArray) ? array_shift($resultArray) : false;
    }

    public static function getBySQL($sql) {
        global $db;
        $result = $db->query($sql);
        $objArray = array();
        while ($row = $db->fetchArray($result)) {
            $objArray[] = self::instantiate($row);
        }
        return $objArray;
    }

    public function getName() {
        if (isset($this->firstname) && isset($this->lastname)) {
            return $this->firstname . " " . $this->lastname;
        } else {
            return "";
        }
    }

    private static function instantiate($record) {
        $object = new self;

        foreach($record as $attr=>$value){
            if($object->hasAttr($attr)) {
                $object->$attr = $value;
            }
        }
        return $object;
    }

    private function hasAttr($attr) {
        $objectVars = get_object_vars($this);
        return array_key_exists($attr, $objectVars);
    }

    public static function verify($username, $password) {
        global $db;
        $username = $db->prepare($username);
        $password = $db->prepare($password);

        $sql = "SELECT * FROM users WHERE username = '{$username}' AND userpass = '{$password}'";
        $resultArray = self::getBySQL($sql);
        return !empty($resultArray) ? array_shift($resultArray) : false;
    }
}

?>

database.php

<?php
include 'config.php';

class Database {
    private $connection;

    function __construct() {
        $this->connect();
    }

    public function connect() {
        $this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
        if(mysqli_connect_errno()) {
            die("Database connection failed: " . 
               mysqli_connect_error() . 
               " (" . mysqli_connect_errno() . ")"
            );
        }
    }

    public function disconnect() {
        if(isset($this->connection)) {
            mysqli_close($this->connection);
            unset($this->connection);
        }
    }

    public function query($sql) {
        $result = mysqli_query($this->connection, $sql);
        if (!$result) {
            die("Database query failed.");
        } 
        return $result;
    }

    public function prepare($data) {
        $escString = mysqli_real_escape_string($this->connection, $data);
        return $escString;
    }

    public function fetchArray($results) {
        return mysqli_fetch_assoc($results);
    }
}

$db = new Database();

?>
马塞诺

PHP无法在请求之间保留变量值。这意味着每次调用脚本时,$ bool-variable都将设置为false。如果要在请求之间保留值,则必须使用会话,或者如果要在会话之间共享变量,则可以使用某些缓存机制,例如APC或Memcache。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章