How can I use cookies in a Joomla component?
setcookie( JUtility::getHash('JLOGIN_REMEMBER'), false, time() - 86400, '/' );
Can anybody describe how this works?
Now, inside your React component, you can access the cookie by using a useCookies () hook. The cookies object is holding the all cookies, you have created in your app.
Using Cookies in Razor Pages Cookies are small pieces of text that are passed between browser and web server with every request. Cookies are commonly used to store relatively small amounts of data such as user preferences which help the site remember which features to turn on or off, for example.
The browser may store the cookie and send it back to the same server with later requests. Typically, an HTTP cookie is used to tell if two requests come from the same browser—keeping a user logged in, for example. It remembers stateful information for the stateless HTTP protocol.
The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header. An expiration date or duration can be specified, after which the cookie is no longer sent.
// Get input cookie object
$inputCookie = JFactory::getApplication()->input->cookie;
// Get cookie data
$value = $inputCookie->get($name = 'myCookie', $defaultValue = null);
// Check that cookie exists
$cookieExists = ($value !== null);
// Set cookie data
$inputCookie->set($name = 'myCookie', $value = '123', $expire = 0);
// Remove cookie
$inputCookie->set('myCookie', null, time() - 1);
$expire
valuetime()
.$expire == 0
: cookie lifetime is of browser session.$expire < time()
: cookie is being deleted (expire set to past).
You could remove cookie by setting it's value to null, but apparently IE fails to do so.Keep in mind that cookies should be set before headers are sent (usually before output is echoed).
Cookie key and value should be properly escaped
When serializing the value on set (like json_encode($dataNode)
), remember to use proper filter to retrieve it later on. Default is cmd
, which filters out pretty much anything but a-Z, 0-9 and cracks JSON structure.
// Get cookie data
$encodedString = $inputCookie->get('myCookie', null, $filter = 'string');
// Decode
$values = json_decode($encodedString);
// Encode and Set
$inputCookie->set('myCookie', json_encode($values));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With