PHP cookie value works only after 2 page loads

2020-05-06 11:55发布

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?

1条回答
甜甜的少女心
2楼-- · 2020-05-06 12:33

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.

查看更多
登录 后发表回答