views:

76

answers:

3

I store an array of values in my cookie as a string (with ',' as separator). I update them using explode(), implode() and setcookie() methods in a custom function set_Cookie() and it works great.

function set_Cookie($name, $position, $value) {
    $cookie = ($_COOKIE[$name]);
    $cookie_exp = explode(",", $cookie);
    $cookie_exp[$position] = $value;
    $cookie_imp = implode(",", $cookie_exp);
    setcookie($name,$cookie_imp);
}


The only problem I have is when I try to call the function multiple times - only the last call succeeds in updating the value. In other words: In the code below only 'position3' would get updated with 'value3' but other positions would not get updated at all:

set_Cookie('cookie1','$position1','value1');
set_Cookie('cookie1','$position2','value2');
set_Cookie('cookie1','$position3','value3');


Initial cookie1 values: 0,0,0

Result: 0,0,value3


What am I missing?

+3  A: 

Calling setcookie doesn't update the value in $_COOKIE.

Greg
Could you elaborate?
est
It actually does update the value, but only in the last call.
est
+1  A: 

Your function takes 3 arguments. It looks like you are not passing the position in your calls. Passing value as second argument will mangle your cookie.

EDIT: Can you please show us your initial value of cookie1 and for each function call what position value you sent and what the result was ? Also, try making only the first two calls and in another case, make 4 calls and see if the situation of value-changes-only-at-last-call persists.

Joy Dutta
Updated the initial cookie values and the result. Maybe it has something to do with sending the cookies in the headers? I don't know i'm puzzled...
est
Yes I already checked it with two, four and more calls. Always the same story.
est
A: 

To put greg's point into code:

function set_Cookie($name, $position, $value) {
    $cookie = ($_COOKIE[$name]);
    $cookie_exp = explode(",", $cookie);
    $cookie_exp[$position] = $value;
    $cookie_imp = implode(",", $cookie_exp);
    setcookie($name,$cookie_imp);

    $_COOKIE[$name] = $cookie_imp;
}
Frank Farmer
Thank you so much man! You saved my day!
est