如何使用组件中的 cookie? [英] How to use cookies from a component?
本文介绍了如何使用组件中的 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Joomla 组件中使用 cookie?
How can I use cookies in a Joomla component?
setcookie( JUtility::getHash('JLOGIN_REMEMBER'), false, time() - 86400, '/' );
有人能描述一下这是如何工作的吗?
Can anybody describe how this works?
推荐答案
// 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
值的一些规则
- 它是一个以秒为单位的 Unix tinestamp,例如
time()<的返回值/code>.
$expire == 0
:cookie 生存期是浏览器会话.$expire
- its a Unix tinestamp in seconds, like return value of
time()
. $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.
Some rules about $expire
value
请记住,应在发送标头之前(通常在回显输出之前)设置 cookie.
Cookie 键和值应该正确转义
在集合上序列化值时(如 json_encode($dataNode)
),请记住使用适当的过滤器稍后检索它.默认为 cmd
,它过滤掉除 a-Z、0-9 之外的几乎所有内容并破解 JSON 结构.
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));
参考
- Joomla CMS github 存储库:JInputCookie::set(有据可查)
- php 文档:php.net/setcookie(开发者体验)
- 维基百科:HTTP Cookies(理论)
- Joomla CMS github repository: JInputCookie::set (very well documented)
- php docs: php.net/setcookie (developer experiences)
- Wikipedia: HTTP Cookies (theory)
Rererences
这篇关于如何使用组件中的 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文