【问题标题】:Cake PHP 2.5.2. sessions reading from database蛋糕 PHP 2.5.2。从数据库读取的会话
【发布时间】:2015-06-29 11:27:00
【问题描述】:

设置为数据库时,我无法从 cake php 会话中读取值,它返回 null。

我已经在core.php中设置了

Configure::write('Session', array(
    'defaults' => 'database'
));

我已经建立了一个 cakephp 会话表,它将会话数据存储在表中。

我试着读回它

$pid = $this->Session->read('Projectid');

我写的

  $this->Session->write('Projectid', key($projects) );

有什么想法吗? 它在使用 php 会话而不是数据库时有效。

数据库sql

   CREATE TABLE IF NOT EXISTS `cake_sessions` (
     `id` varchar(255) NOT NULL,
   `data` text,
  `expires` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

更新

我发现如果我删除将列表写入会话的行,它可以读取其他变量。这是一个错误吗?

 $projects =   $this->Project->find('list', array('fields' => array('id','name')
$this->Session->write('Projects', $projects); //removing this line i can read

【问题讨论】:

    标签: php database session cakephp


    【解决方案1】:

    使用 CakePHP 2.3 我正在试验同样的问题,无法使用默认数据库配置在 Session 中写入或读取。

    然后,我关注了这个示例,Custom Handler CakePHP Session,但我无法访问服务器以正确配置 php-apc,所以我只是从示例中删除了 apc 功能。

    我在 app/Model/Datasource/Session/CustomSessionHandler.php(示例中的 ComboSession)中的最终代码如下所示。

    <?php
    
    App::uses('DatabaseSession', 'Model/Datasource/Session');
    
    class CustomSessionHandler extends DatabaseSession implements     CakeSessionHandlerInterface {
        public $cacheKey;
    
        public function __construct() {
            parent::__construct();
        }
    
        // read data from the session.
        public function read($id) {
            $result = Cache::read($id);
            if ($result) {
                return $result;
            }
            return parent::read($id);
        }
    
        // write data into the session.
        public function write($id, $data) {
            Cache::write($id, $data);
            return parent::write($id, $data);
        }
    
        // destroy a session.
        public function destroy($id) {
            Cache::delete($id);
            return parent::destroy($id);
        }
    
        // removes expired sessions.
        public function gc($expires = null) {
            Cache::gc();
            return parent::gc($expires);
        }
    }
    

    我的 app/Config/core.php 会话配置部分。

    Configure::write('Session', array(
      'defaults' => 'database',
      'handler' => array(
          'engine' => 'CustomSessionHandler',
          'model'  => 'Session'
       )
    ));
    

    最后我创建表来存储会话。

    CREATE TABLE `sessions` (
      `id` varchar(255) NOT NULL DEFAULT '',
      `data` text,
      `expires` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    );
    

    完成这些步骤后,现在我可以毫无问题地读取和写入 Session,并且我的会话存储在“会话”表中。

    【讨论】:

    • 感谢您的回答,但我发现问题出在我的回答中
    【解决方案2】:

    问题是我在表中使用日文但未设置为 UTF-8,这导致将会话保存到数据库时出现问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多