Delete a cookie if the key start by X in PHP

2019-06-02 09:51发布

I got some cookie start by XYZ and I want to unset them when the user access to a specific route.

So I code :

foreach ($_COOKIE as $key => $value)
        if (preg_match('/^XYZ/', $key))
            unset($_COOKIE[$key]);

But the cookies still there. I really don't understand because when I do :

foreach ($_COOKIE as $key => $value)
        if (preg_match('/^XYZ/', $key))
            echo($_COOKIE[$key]);

... it works. So I wonder if it is possible to unset cookies like above.

2条回答
萌系小妹纸
2楼-- · 2019-06-02 10:08

reset a cookie like:

setcookie($key,"",time()-3600);
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-06-02 10:28

You can try this -

foreach ($_COOKIE as $key => $value) {
    if (strpos($key, 'XYZ') === 0) { // check if name starts with 'XYZ'
         setcookie($key, "", (time() - 3600) ); // Set the time which already expired
    }
}

With preg_match -

if (preg_match('/^XYZ/', $key)) {
     setcookie($key, "", (time() - 3600) );
}
查看更多
登录 后发表回答