I cannot read values from cake php sessions when set to database, it returns null.
I have set in core.php
Configure::write('Session', array(
'defaults' => 'database'
));
I have setup a cakephp sessions table , it stores session data in the table.
I try to read it back with
$pid = $this->Session->read('Projectid');
I write it with
$this->Session->write('Projectid', key($projects) );
Any ideas? It works when using php sessions but not database.
Database 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
I found that if i remove a line that writes a list to the session, it can read other variables.Is this a bug?
$projects = $this->Project->find('list', array('fields' => array('id','name')
$this->Session->write('Projects', $projects); //removing this line i can read
The problem was i was using Japanese in a table but it was not set to UTF-8, this was causing issues with saving sessions to db.
Using CakePHP 2.3 i was experimenting the same issue, was not able to write or read in Session using defaults database config.
Then, i followed this sample, Custom Handler CakePHP Session, but i has not access to the server in order to configure php-apc properly, so, just i removed the apc feature from the sample.
My final code in app/Model/Datasource/Session/CustomSessionHandler.php (ComboSession in the sample) looks like this.
<?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);
}
}
My app/Config/core.php session config section.
Configure::write('Session', array(
'defaults' => 'database',
'handler' => array(
'engine' => 'CustomSessionHandler',
'model' => 'Session'
)
));
And finally my table creation to store sessions.
CREATE TABLE `sessions` (
`id` varchar(255) NOT NULL DEFAULT '',
`data` text,
`expires` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);
After this steps, now i can read from and write to Session, without any issues, and my sessions are stored in 'sessions' table.