PHP Cookie值仅在加载2个网页后才有效 [英] PHP cookie value works only after 2 page loads

查看:99
本文介绍了PHP Cookie值仅在加载2个网页后才有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这可能是一个非常初级的问题,但我只是一个月的PHP,所以请承担与我。我试图在WordPress博客中设置一个cookie。 Cookie从URL接收其值。 http://www.xyz.com/?name=John



这是Cookie的设置方式:

  function set_name_cookie(){
if(isset($ _ GET ['name'])){
$ name = $ _GET ['name' ];
setcookie(name,$ name,time()+ 3600,/,.xyz.com,false);
}
}
add_action('init','set_name_cookie');

HTML + PHP:

 <?php if(isset($ _ COOKIE ['name'])){
$ name = $ _COOKIE ['name'];
echo $ name;
?>
< a href =?name = John> John< / a>
< a href =?name = Smith>史密斯< / a>问题是,当我点击链接John或Smith中的任何一个链接时,都会出现一个错误。页面加载,但名称未回显。 我必须重新刷新才能回显名称。流有一些问题。帮助?

解决方案

设置cookie时,不会填充 $ _ COOKIE 在该网页加载,因为该变量从浏览器发送给您的负载。一个解决方法是在 setcookie 语句后面设置 $ _ COOKIE ['name'] = $ name; 但这不保证浏览器接受并实际设置cookie - 只是一种方法,使其立即可用您的脚本。


I know this might be an extremely beginner level question but I am just a month into PHP so please bear with me. I am trying to set a cookie in a WordPress blog. The cookie receives its value from URL. "http://www.xyz.com/?name=John"

This is how the cookie is being set:

function set_name_cookie() {
    if (isset($_GET['name'])) {
        $name = $_GET['name'];
        setcookie("name", $name, time()+3600, "/", ".xyz.com", false);
    }
}
add_action( 'init', 'set_name_cookie');

HTML + PHP:

<?php if(isset($_COOKIE['name'])) {
      $name = $_COOKIE['name'];
      echo $name; 
?>
<a href="?name=John">John</a>
<a href="?name=Smith">Smith</a>

The problem is, when I click the either of the links "John" or "Smith", the page loads but the name is not echoed. I have to refresh again for the name to echo. There is some problem with the flow. Help?

解决方案

When you set a cookie, it doesn't populate $_COOKIE on that page load, as that variable is loaded from what the browser sends you. A workaround for that would be to set $_COOKIE['name'] = $name; after your setcookie statement - but that does not guarantee that the browser accepted and actually set the cookie - just a way to make it available immediately in your script.

这篇关于PHP Cookie值仅在加载2个网页后才有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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