【问题标题】:PHP session - Attach a class instancePHP session - 附加一个类实例
【发布时间】:2013-10-28 08:35:11
【问题描述】:

对于一个小型的个人项目,我需要将一个类实例附加到一个 PHP 会话中。 为此,我编写了以下代码,但它并没有像我预期的那样工作。例如,当我调用方法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 实例。

感谢您的帮助。

【问题讨论】:

    标签: php class session


    【解决方案1】:

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

    只需将用户名、时间戳、用户 ID 和密码保存到会话中..

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

    【讨论】:

    • 我不明白你的意思。你能解释一下吗?
    • 伙计,我从未听说有人将实例保存到会话中。他们所做的只是使用 spl_autoload 函数
    • 嗯,我需要在每个页面上传递用户名、时间戳、用户 ID 和密码来检查用户是否连接。这就是为什么我需要将实例存储到会话中。这不是我第一次看到。如果你用谷歌搜索,很多人都在这样做。
    • 只需将用户名、时间戳、用户 ID 和密码保存到会话中。$_SESSION['instance'] = json_encode(array('username', 'timestamp', 'userid','password') );
    猜你喜欢
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 1970-01-01
    • 2016-01-16
    • 2015-02-27
    • 1970-01-01
    相关资源
    最近更新 更多