currently i am modifying an existing CakePhp project and i'd like to set a cookie in a开发者_StackOverflow中文版 specific page of the project (it has a .ctp file) so first i've tried to put the setcookie php code in the top of the .ctp template (before doctype tag as i'd do in a normal php website) but it doesn't work, no cookie is set.
So my question is, how could i add a cookie to the visitor when hits X page (which its template file is called list.ctp (for example)) of the website?
Thanks a lot to everyone!
set Cookie on components variable in controller
var $components = array('Cookie');
In any action, you can write cookie with
$this->Cookie->write('anyname', cookieData, $encrypt = false, $expires = null);
To read stored cookie, just call this code
$this->Cookie->read('anyname');
Also you can find additional information from the cakephp's documents: http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html
You would set the cookie in the controller for whatever view/page you want the cookie set. So if the .ctp file in in the users directory then you would set the cookie in the users_controller.php in the function named like your .ctp file: users/index.ctp add the cookie to controllers/users_controller.php in the index function.
精彩评论