Cookies allow you to persist data across requests, thus allowing you to keep track of certain aspects of the navigation, user, or anything that needs to be referenced from one action to another.
In this recipe, we'll create a basic example scenario that shows how to use cookies in the framework.
For this recipe, we'll use a controller to work with, so let's use our existing ExampleController.php
file in app/Controller/
. We'll also need a view for one of our actions, so also create a file named cookie.ctp
in app/View/Example/
.
Perform the following steps:
Add the
$components
property to theExampleController
class with theCookie
component, as shown in the following code:public $components = array( 'Cookie' => array( 'time' => '+1 day' ) );
Define the following
cookie()
method:public function cookie() { $value = __('No value defined'); if ($this->Cookie->check('value')) { $value = $this->Cookie->read('value'); ...