开发者

PHP setcookie() does not work after unsetting $_COOKIE

I've just written very simple wrapper class for Cookies, which goes as follow:

<?php
class Cookie {  

    // expire time of the cookie 31 days
    private static $_expire = '2678400';

    public static function set($name = null, $value = null, $expire = null) {
        if (!empty($name)) {
            $expire = !empty($expire) ? $expire : time() + self::$_expire;
            if (setcookie($name, $value, $expire)) {
                return true;
            }
            return false;
        }
        return false;
    }

    public static function get($name = null) {
        if (!empty($name)) {
            return !empty($_COOKIE[$name]) ? $_COOKIE[$name] : false;
        }
        return false;
    }      

    public static function remove($name = null) {
        if (!empty($name)) {
            if (!empty($_COOKIE[$name])) {
                if (setcookie($name, false, time() - self::$_expire)) {
                    unset($_COOKIE[$name]);
      开发者_JAVA技巧              return true;
                }
                return false;
            }
            return true;
        }
        return false;
    }

}
?>

However I have a problem when the cookie was initially set, then I want to change the value by first calling :

Cookie::remove('session_name');

and then

Cookie::set('session_name');

The second one (set) doesn't set the cookie.

Any idea what might be causing it?


I think you misunderstand how cookies work.

The contents of $_COOKIE are set once, when the HTTP request arrives and before your script starts execution.

If you use setcookie to add or modify a cookie, this addition or modification will not be visible until the next HTTP request to your server. This is what you are doing in your Cookie::set method.

If you are "testing" Cookie::set by looking at the contents of $_COOKIE (or by using Cookie::get, which does the same thing) then you will not see the changes to the cookie even though they have been made.

To see what you expect, you should add the value to $_COOKIE inside Cookie::set. However, I would suggest writing your program in a different manner. You are trying to use cookies like normal variables, which they are not.


if you whant to change the value of a cookie , there is no need to first remove it , you can call straight Session::set('session_name'); and the cookie would be overwrited . call Session::remove('session_name'); only when you don't need the cookie anymore.


if I correctly understood you , you need something like that

public static function set($name, $value,$expire) 
{
    setcookie($name, $value, $expire);

   $_COOKIE[$name] = $value;    

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜