简体   繁体   中英

PHP Cookie and browser refresh confusion

I have this code here and I noticed when I changed the value to something else. I have to refresh the page not once but twice in order to see the new value.

Is this related to HTTP headers and super globals? or something why do I have to refresh twice to see the new value why is not one refresh? I've tried reading similar questions on other threads but still not clear on this manner as far why? and what's doing. Can someone give me a clear explanation, thank you.

<?php
$name = "test";
$value = "hello";
$expire = time() + (60*60*24*7); 
setcookie($name, $value, $expire);    
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>PHP</title>
</head>
<body>

<?php 
$test = isset($_COOKIE["test"]) ? $_COOKIE["test"] : ""; 
echo $test;
?>
</body>

so If I change the value to say 500 then I have to refresh twice to see the new value on the page.

The answer is here https://stackoverflow.com/a/17085896/2243372 .

Try to refresh your page programmatically. Example:

<?php

if (isset($_COOKIE['test'])) {
    echo 'COOKIE = ', $_COOKIE['test'];
} else {
    setcookie('test', 'my-cookie-value', strtotime('+1 day'));
    if ( ! isset($_GET['setcookie'])) {
        header('Refresh: 0; url=?setcookie=done');
    } else {
        echo 'Your browser does not accept cookies!';
    }
}

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