Delete a cookie if the key start by X in PHP

2019-06-02 09:22发布

问题:

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.

回答1:

reset a cookie like:

setcookie($key,"",time()-3600);


回答2:

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