单击设置PHP cookie

时间:2013-01-16 20:02:43

标签: php cookies

所以我宁愿不使用JS / jQuery - 但我似乎无法让它工作。

我有一个链接<a href="?hideupdates=hide">Hide Updates</a>,我正在尝试设置Cookie。

if($_GET['hideupdates'] == 'hide'){
    setcookie("HideUpdates", "hide", time()+60*60*24*5, "/", $vars->networkSite);
}

它“有效”,但我必须点击两次链接。


来自“ site.com ”我可以var_dump() Cookie NULL

现在,我点击该链接转到“ site.com?hideupdates=hide ”,Cookie仍然显示NULL

然而,当我再次点击该链接时,从“ site.com?hideupdates=hide ” - 然后Cookie返回hide

我错过了什么吗?或者我是否'必须'使用JS / jQuery?

3 个答案:

答案 0 :(得分:8)

setcookie不会影响当前请求。为此,您还需要手动设置相关的$_COOKIE变量:

setcookie("HideUpdates",$_COOKIE['HideUpdates'] = "hide", time()+60*60*24*5, "/", $vars->networkSite);

答案 1 :(得分:3)

唯一的方法是使用JS或jQuery ,因为正如其他人所说,Cookie不会影响当前的页面请求。

jQuery解决方案需要jquery cookie plugin某些服务器遇到jquery.cookie.js 的问题(解决方案是重命名文件E.g。:jquery.cook.js)

使用jquery cookie插件

创建会话cookie:

 $.cookie('the_cookie', 'the_value');

从那时起7天内创建过期的Cookie:

 $.cookie('the_cookie', 'the_value', { expires: 7 });

创建过期的Cookie,在整个网站上有效:

 $.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

阅读Cookie:

 $.cookie('the_cookie'); // => "the_value"
 $.cookie('not_existing'); // => undefined

阅读所有可用的Cookie:

 $.cookie(); // => { "the_cookie": "the_value", "...remaining": "cookies" }

删除Cookie:

 // Returns true when cookie was found, false when no cookie was found...
 $.removeCookie('the_cookie');

//与写入cookie时的路径相同...

 $.removeCookie('the_cookie', { path: '/' });

您可以尝试localStorage。它适用于Chrome,FF和IE9及以上版本。我们不支持IE7-10!万岁!

IE8与localStorage存在一些问题。

脚本必须在$(document).ready(function(){});

$(document).ready(function() {
   $("#btnClick").click(function(e) {
      e.preventDefault();
      localStorage.setItem('cookieName', 'cookie_value');
  window.href.location = "your_new_page.php";   
   });


   //On the same page or other page

   if (localStorage.getItem('cookieName')){
      //do here what you want


   }else{
      //do something else

   }

});

答案 2 :(得分:1)

在设置Cookie并发送新页面请求之前,Cookie不会启动。这是因为cookie是随页面请求一起发送的,它们不会神奇地出现在服务器上。

您的解决方案是在设置Cookie后进行页面刷新。

相关问题