PHP会话 - 附加一个类实例

时间:2013-10-19 15:21:26

标签: php class session

对于一个小型的个人项目,我需要将一个类实例附加到PHP Session中。 为此,我编写了以下代码,但它没有像我期望的那样工作。例如,当我调用方法login并刷新页面时,我的类中没有修改任何内容。我的意思是,就像每次重置一样。

我的问题是:如何使用PHP会话在我的页面之间共享Core实例?

    <?php

class Core
{
    /* Database */
    private $db = null;

    /* User activity */
    private $loggedin = false;
    private $userid = 0;
    private $username = null;
    private $password = null;
    private $lastActivity = null;

    /* Constructor */
    public function __construct()
    {
        $this->connect();
    }

    /* Serialize */
    public function __sleep()
    {
        return array('loggedin', 'userid', 'username', 'password', 'lastActivity');
    }

    /* Unserialize */
    public function __wakeup()
    {
        $this->connect();
    }

    /* Connect to database */
    private function connect()
    {
        global $DB_HOSTNAME, $DB_BASENAME, $DB_USERNAME, $DB_PASSWORD;

        try
        {
            $this->db = $db = new PDO('mysql:host='.$DB_HOSTNAME.';dbname='.$DB_BASENAME.';charset=utf8', $DB_USERNAME, $DB_PASSWORD);
            $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch (Exception $e)
        {
            die('Erreur : ' . $e->getMessage());
        }
    }

    /* Get database */
    public function getDb()
    {
        return $this->db;
    }

    /* Create a new login session */
    public function login($userid, $username, $password)
    {
        $this->loggedin = true;
        $this->userid = intval($userid);
        $this->username = $username;
        $this->password = $password;
        $this->lastActivity = time();
    }

    /* Close the login session */
    public function logout()
    {
        $this->loggedin = false;
        $this->userid = 0;
        $this->username = null;
        $this->password = null;
    }

    /* Check if the session is running or not */
    public function isConnected()
    {
        if ($this->loggedin)
        {
            if ($this->lastActivity + 3600 < time())
            {
                $this->logout();
                return false;
            }
            elseif (isset($this->password))
            {
                $db = $this->db;
                $query = $db->prepare('SELECT id FROM ptc_users WHERE id=:userid AND password=:password LIMIT 1;');
                $query->bindParam(':userid', $this->userid, PDO::PARAM_INT);
                $query->bindParam(':password', $this->password, PDO::PARAM_STR);
                $query->execute();

                if ($query->rowCount() == 1)
                {
                    $this->lastActivity = time();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        return false;
    }

    /* Return the current user id */
    public function getUid()
    {
        return $this->userid;
    }

    /* Return the current username */
    public function getUsername()
    {
        return $this->username;
    }

    /* Return the hash signature of the password */
    public function hash($input)
    {
        return sha1('minad8rBxu' .$input. 'MigdVKXUCf');
    }

    /* Return the user's ip */
    public function getIp()
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR'];
        else return $_SERVER['REMOTE_ADDR'];
    }
}

// Create a new core session if not started before
if (!isset($_SESSION)) session_start();
if (!isset($_SESSION['core']))
{
    $core = new Core();
    $_SESSION['core'] = serialize($core);
}
else
{
    $core = unserialize($_SESSION['core']);
}

?>

我正在使用魔术方法__sleep__wakeup来避免序列化PDO实例。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

实例化或自动加载Core类,以便您可以在整个应用程序中使用它。不需要session ..或者只是将类名保存到session ...

只需将用户名,时间戳,用户ID和密码保存到会话中即可。

    $_SESSION['instance'] = json_encode(array('username', 'timestamp', 'userid','password'));

$object = json_decode($_SESSION['instance']);

echo var_dump($object);