0

I'm writing a class to control how cookies are handled for a custom CMS I'm working on and I was curious as to the best approach to updating a cookie once it's been created. Below I've pasted a function from my class that I'm using to currently update cookies but it doesn't seem to be working properly. The issue I'm having is that the cookie does not seem to change even though this function returns "true".

    function updateCookie($data){
            $cookieArray = $this->getCookie();
            array_push($cookieArray,$data);
            //print_r($cookieArray);
            $json_string = json_encode($cookieArray,true);
            if(setcookie(_COOKIENAME, $this->encodeString($json_string,"S33D"))){
                return true;
            }
            else return false;
        }

Suggestions or corrections would be helpful.

Thanks

TheSnooker
  • 935
  • 2
  • 11
  • 24

1 Answers1

0

Some hints from the documentation that may be of help:

If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

...

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. If you don't want this, you can use setrawcookie() instead if you are using PHP 5.

http://php.net/manual/en/function.setcookie.php

And some knitpicking: setcookie returns a boolean so no need to do the check. Just do:

return setcookie( ... );
Whistletoe
  • 573
  • 2
  • 10
  • That's disappointing that it will return TRUE even if the cookie is not accepted. I am starting to wonder if using a cookie is the best approach for this. There are other NON-DATABASE persistent storage options. WEB-SQL... and... lol I think that's all i can think of – TheSnooker Apr 10 '13 at 20:12
  • Here is some info on checking if the user accepts cookies: http://www.pelaphptutorials.com/article/php-checking-to-see-if-a-users-browser-accepts-cookies.html – Whistletoe Apr 10 '13 at 20:22