开发者

Multiple function calls, only the last succeeds. Why?

开发者 https://www.devze.com 2022-12-12 02:28 出处:网络
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.

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 g开发者_Go百科et 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?


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


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.


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;
}
0

精彩评论

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