Delete a cookie if the key start by X in PHP

青春壹個敷衍的年華 提交于 2019-12-23 03:41:58

问题


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


来源:https://stackoverflow.com/questions/34018480/delete-a-cookie-if-the-key-start-by-x-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!