会话在课堂上启动php

时间:2014-11-12 17:17:33

标签: php

是否可以在类方法中启动会话? 以下(在类的方法中)不起作用:

// some code here
session_start();

// Pass user data to session
$user = new User($row->nif, $row->name);
$_SESSION["user"] = $user;
return $user;

当我这样做时,在session_start之后:

isset($_SESSION);

我弄错了。

修改

这是我的班级代码

class UserDAO {
    private static $AUTHENTICATE_USER_QUERY = "SELECT * FROM pessoa WHERE nif = :username";

    /**
     * Authenticate a user. Returns the authenticated user or null.
     * May throw exceptions.
     * @param type $username
     * @param type $password
     */
        public function authenticateUser($connection, $username, $password) {
        $stmt = $connection->prepare(self::$AUTHENTICATE_USER_QUERY);
        $stmt->bindParam(":username", $username, PDO::PARAM_STR);
        $stmt->execute(); 

        // Authenticate user
        $rows = $stmt->fetchAll(PDO::FETCH_OBJ);
        foreach($rows as $row) {
            if($row->pin == $password) {
                // Valid user
                session_start();

                // Pass user data to session
                $user = new User($row->nif, $row->name);
                $_SESSION["user"] = $user;
                return $user;
            }
        }

        // Invalid user
        return null;
    }

    /**
     * Assert if the user has a session.
     */
    public function isAuthenticated() {
        return session_id() !== '';
    }

    /**
     * Destroy user session.
     */
    public function logoutUser() {
        session_unset(); 
        session_destroy();
    }
}

以下是我在login.php中使用它的方法:

$manager = new DBManager();
$userDAO = new UserDAO();

$user = $userDAO->authenticateUser($manager->getConnection(), $username, $password);

在我的index.php中,我有:

$userDAO = new UserDAO(); 

if ($userDAO->isAuthenticated()) {
                // The client has a session (so it's authenticated)
                header("Location: home.php");
                exit;
            } 

0 个答案:

没有答案