
Question:
I am trying to write session in controller. My structure is
$_SESSION['a'][0] = 1;
$_SESSION['a'][1] = 2;
$_SESSION['a'][2] = 3;
And I am trying this
Configure::write('Session', ['a' =>'1'])
But it is not working. How do this in cakephp 3 way
Answer1:To write variable in Session in CakePHP 3 you need to write following code :
$this->request->session()->write('Your Key',Your_array);
To know more information you can visit here :
<a href="http://book.cakephp.org/3.0/en/development/sessions.html" rel="nofollow">http://book.cakephp.org/3.0/en/development/sessions.html</a>
Answer2:You can simply use
$session->write([
'key1' => 'blue',
'key2' => 'green',
]);
I am refering to
<a href="http://book.cakephp.org/3.0/en/development/sessions.html#reading-writing-session-data" rel="nofollow">http://book.cakephp.org/3.0/en/development/sessions.html#reading-writing-session-data</a>
Answer3:<strong>The answer is that this cannot be done in CakePHP 3.x</strong>
In vanilla PHP, it's possible to do this:
<?php
session_start();
$_SESSION['a'][0] = 1;
$_SESSION['a'][1] = 2;
$_SESSION['a'][2] = 3;
var_dump($_SESSION);
?>
Which will output:
array(1) {
["a"]=> array(3) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
}
}
This is correct, and what <em>should</em> happen.
In CakePHP, you cannot specify arrays in the session key. For example:
$this->request->session()->write('a[]', 1);
$this->request->session()->write('a[]', 2);
$this->request->session()->write('a[]', 3);
Will not work.
If you remove the []
<strong>the value will get overwritten</strong>. For example:
$this->request->session()->write('a', 1);
$this->request->session()->write('a', 2);
$this->request->session()->write('a', 3);
The value of $this->request->session()->read('a')
would be 3
. The values 1
and 2
have been overwritten. Again, this is to be expected because you're overwriting the key a
each time. The equivalent vanilla PHP for this is:
$_SESSION['a'] = 1;
$_SESSION['a'] = 2;
$_SESSION['a'] = 3;
Due to the lack of an indexed array, $_SESSION['a']
gets overwritten each time. This is normal behaviour. It needs to have the indexes (e.g. ['a'][0], ['a'][1], ...
) to work!
The other answers where they have given things like key1
and key2
are not appropriate. Because there are many situations where you want everything contained within an indexed array. Generating separate key names is wrong for this type of scenario.