简体   繁体   English

无法设置CodeIgniter Cookie,但会话正常工作吗?

[英]CodeIgniter Cookie won't set but Session is working?

I'm working with CodeIgniter to set up some user login functions to my site using Twitter and Facebook, this parts working and the session works fine. 我正在与CodeIgniter一起使用Twitter和Facebook设置一些用户登录功能到我的网站,此部分正常工作,并且会话正常进行。

When I try to set a cookie it doesn't work 当我尝试设置Cookie时不起作用

//Setup a guid
$guid = uniqid();

//Setup a random cookie and point it to db user
$cookie = array(
  'name'   => 'TheCookieName',
  'value'  => $guid,
  'expire' => 100,
  'domain' => BASE_URL,
  'secure' => TRUE
);

    set_cookie($cookie);

  var_dump(get_cookie('TheCookieName')); // bool(false)

My autoload file is simple enough 我的自动加载文件非常简单

$autoload['helper'] = array('paging_helper','url','cookie');

I'm obviously missing something trivial? 我显然缺少一些琐碎的东西? Any clue? 有什么线索吗?

Thanks 谢谢

确保仅对https设置secure => TRUE

The problem is probably within your domain variable BASE_URL, which isn't a part of CI constants, probably doesn't contain what you expect or what a cookie initialization requires. 问题可能出在您的域变量BASE_URL中,该变量不是CI常量的一部分,可能不包含您期望的内容或cookie初始化所需的内容。

Try doing it like this: 尝试这样做:

//Setup a guid
$guid = uniqid();

//Setup a random cookie and point it to db user
$cookie = array(
  'name'   => 'TheCookieName',
  'value'  => $guid,
  'expire' => 86500, // have a high cookie time till you make sure you actually set the cookie
  'domain' => '.example.org', // the first . to make sure subdomains isn't a problem
  'path' => '/',
  'secure' => TRUE
);

    set_cookie($cookie);

Remember that cookies will never be available until a new request have been made. 请记住,在发出新请求之前,cookie永远不会可用。
Redirect to another page on the domain specified in the cookie setup and check for the cookie again. 重定向到cookie设置中指定的域上的另一个页面,然后再次检查cookie。

You cannot set and access a cookie in the same instance. 您不能在同一实例中设置和访问Cookie。 You should either redirect after setting the cookie or refresh. 您应该在设置Cookie后重定向或刷新。 That's the reason why var_dumping get_cookie would always return false. 这就是var_dumping get_cookie总是返回false的原因。 You should also set the rest of the arguments. 您还应该设置其余参数。 See setcookie setcookie

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM