Cakephp: Reading cookie problem
I am using the jQuery cookie plugin to set a cookie called 'orderStatus' with a value of '开发者_运维百科success'. This is working find and I have checked and the cookie is set correctly and present. However when I come to read the cookie in my controller like so:
$status = $this->Cookie->read('orderStatus');
and then echo the contents of $status its empty. Anyone know what I'm doing wrong? I've set cake to use the cookie component so thats not the problem. Thanks
The answer is, unfortunately, you can not read a cookie that was written by any other method using cakephp. The Cookie component in cake was not written with interoperability in mind. The read method can only read cookies that were written by the cake cookie component methods.
In order to read a cookie set by javascript in your controller, you have to access the $_COOKIE variable native to PHP.
It will work if you use the same namespace for your cookie saved by JavaScript that is used by Cake Cookie Component as default. The namespace is 'CakeCookie'
So your cookie must look something like:
CakeCookie[your_cookie_name]
Are you able to set other cookie values? What's the output from the following code?
<?php
function testcookie() {
$this->Cookie->write( 'test', 'somevalue' );
echo $this->Cookie->read( 'test' );
}
?>
First of all, that might represent a big risk for your application. Remember, a cookie is data a user can modify by themselves. So if that's the validation, there may be an error.
Now, I don't know if you are setting the cookie, but the way to set the cookies in CakePHP is via a Model.field
syntax:
$this->Cookie->read('Order.status');
Try setting a cookie above the same controller, now try reading it and then start backtracing it.
You can read jQuery Cookies from CakePhp, the only problem is that they can not be encrypted.
If you are using for example jCookie (https://github.com/carhartl/jquery-cookie), the code bellow will work for you, replace myCompany with your Cookie name from config file.
$.cookie.raw = true;
$.cookie('myCompany[cookie_name]', 'hallo', { expires: 365, path: '/'});
Then, in your controller:
$this->Cookie->check('cookie_name')
will return true (cakephp > 2.2) and
$this->Cookie->read('cookie_name')
will return 'hallo'
If using cakephp 3.x this should be like :
$this->Cookie->read('CakeCookie.cookie_name')
精彩评论