Remove a cookie

后端 未结 22 1256
没有蜡笔的小新
没有蜡笔的小新 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:38

    To delete cookie you just need to set the value to NULL:

    "If you've set a cookie with nondefault values for an expiration time, path, or domain, you must provide those same values again when you delete the cookie for the cookie to be deleted properly." Quote from "Learning PHP5" book.

    So this code should work(works for me):

    Setting the cookie: setcookie('foo', 'bar', time() + 60 * 5);

    Deleting the cookie: setcookie('foo', '', time() + 60 * 5);

    But i noticed that everybody is setting the expiry date to past, is that necessary, and why?

    0 讨论(0)
  • 2020-11-22 16:41

    I had the same problem in my code and found that it was a cookie path issue. Check out this stack overflow post: Can't delete php set cookie

    I had set the cookie using a path value of "/", but didn't have any path value when I tried to clear it, so it didn't clear. So here is an example of what worked:

    Setting the cookie:

    $cookiePath = "/";
    $cookieExpire = time()+(60*60*24);//one day -> seconds*minutes*hours
    setcookie("CookieName",$cookieValue,$cookieExpire,$cookiePath);
    

    Clearing the cookie:

    setcookie("cookieName","", time()-3600, $cookiePath);
    unset ($_COOKIE['cookieName']);
    

    Hope that helps.

    0 讨论(0)
  • 2020-11-22 16:43

    If you set the cookie to expire in the past, the browser will remove it. See setcookie() delete example at php.net

    0 讨论(0)
  • You can simply use this customize function:

    function unset_cookie($cookie_name) {
        if (isset($_COOKIE[$cookie_name])) {
            unset($_COOKIE[$cookie_name]);
            setcookie($cookie_name, null, -1);
        } else { return false; }
    }
    

    If you want to remove $_COOKIE['user_account'].
    Just use:

    unset_cookie('user_account');
    
    0 讨论(0)
  • 2020-11-22 16:49

    You May Try this

    if (isset($_COOKIE['remember_user'])) {
        unset($_COOKIE['remember_user']); 
        setcookie('remember_user', null, -1, '/'); 
        return true;
    } else {
        return false;
    }
    
    0 讨论(0)
  • 2020-11-22 16:49

    To remove all cookies you could write:

    foreach ($_COOKIE as $key => $value) {
        unset($value);
        setcookie($key, '', time() - 3600);
    }
    
    0 讨论(0)
提交回复
热议问题