开发者

Setting new cookies on CakePHP

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!


  1. set Cookie on components variable in controller

    var $components = array('Cookie');

  2. In any action, you can write cookie with

    $this->Cookie->write('anyname', cookieData, $encrypt = false, $expires = null);

  3. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜