2015-04-22 37 views
0

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

我在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; 

UPDATE

我发现,如果我删除开单到会话一条线,它可以读取其他variables.Is这一个错误?

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

回答

0

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

0

使用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`) 
); 

完成此步骤后,现在我可以读取和写入会话,没有任何问题,我的会话存储在'会话'表中。

+0

感谢您的回答,但我发现问题实际上是看到我的答案 – tsukimi