简体   繁体   中英

PHP cookie value works only after 2 page loads

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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