简体   繁体   中英

Delete a cookie if the key start by X in PHP

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.

重设Cookie,例如:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM