Remove a cookie

后端 未结 22 1297
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 16:16

When I want to remove a Cookie I try

unset($_COOKIE[\'hello\']);

I see in my cookie browser from firefox that the cookie still exists. How

相关标签:
22条回答
  • 2020-11-22 16:52

    You could set a session variable based on cookie values

    session_start();
    
    if(isset($_COOKIE['loggedin']) && ($_COOKIE['loggedin'] == "true") ){
    $_SESSION['loggedin'] = "true";
    }
    
    echo ($_SESSION['loggedin'] == "true" ? "You are logged in" : "Please Login to continue");
    
    0 讨论(0)
  • 2020-11-22 16:53
    $cookie_name = "my cookie";
    $cookie_value = "my value";
    $cookie_new_value = "my new value";
    
    // Create a cookie,
    setcookie($cookie_name, $cookie_value , time() + (86400 * 30), "/"); //86400 = 24 hours in seconds
    
    // Get value in a cookie,
    $cookie_value = $_COOKIE[$cookie_name];
    
    // Update a cookie,
    setcookie($cookie_name, $cookie_new_value , time() + (86400 * 30), "/");
    
    // Delete a cookie,
    setcookie($cookie_name, '' , time() - 3600, "/"); //  time() - 3600 means, set the cookie expiration date to the past hour.
    
    0 讨论(0)
  • 2020-11-22 16:54

    To reliably delete a cookie it's not enough to set it to expire anytime in the past, as computed by your PHP server. This is because client computers can and often do have times which differ from that of your server.

    The best practice is to overwrite the current cookie with a blank cookie which expires one second in the future after the epoch (1 January 1970 00:00:00 UTC), as so:

    setcookie("hello", "", 1);
    
    0 讨论(0)
  • 2020-11-22 16:54

    This is how PHP v7 setcookie() code works when you do:

    <?php
        setcookie('user_id','');
        setcookie('session','');
    ?>
    

    From the output of tcpdump while sniffing on the port 80, the server sends to the client (Browser) the following HTTP headers:

    Set-Cookie: user_id=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0
    Set-Cookie: session=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0
    

    Observing packets in the following requests the Browser no longer sends these cookies in the headers

    0 讨论(0)
提交回复
热议问题