如何使用组件中的cookie? [英] How to use cookies from a component?

查看:161
本文介绍了如何使用组件中的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().
  • $expire == 0:cookie生存期与浏览器会话有关.
  • $expire < time():正在删除cookie(过期设置为过去). 您可以通过将cookie的值设置为null来删除cookie,但是显然IE无法做到这一点.
  • Some rules about $expire value

    • 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.
    • 请记住,应该在发送标题之前(通常在回显输出之前)设置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 cookie (理论上)
      • Rererences

        • Joomla CMS github repository: JInputCookie::set (very well documented)
        • php docs: php.net/setcookie (developer experiences)
        • Wikipedia: HTTP Cookies (theory)
        • 这篇关于如何使用组件中的cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆