我将如何测试是否使用 php 设置了 cookie,如果未设置,则什么也不做

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5859333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:42:57  来源:igfitidea点击:

How would I test if a cookie is set using php and if it's not set do nothing

phpcookies

提问by Aaron

I've tried

我试过了

 $cookie = $_COOKIE['cookie'];

if the cookie is not set it will give me an error

如果 cookie 没有设置它会给我一个错误

PHP ERROR
Undefined index: cookie

How would I prevent it from giving me an empty variable>

我将如何防止它给我一个空变量>

回答by Rocket Hazmat

Use issetto see if the cookie exists.

使用isset看是否cookie存在。

if(isset($_COOKIE['cookie'])){
    $cookie = $_COOKIE['cookie'];
}
else{
    // Cookie is not set
}

回答by John Parker

You can use array_key_existsfor this purpose as follows:

为此,您可以使用array_key_exists,如下所示:

$cookie = array_key_exists('cookie', $_COOKIE) ? $_COOKIE['cookie'] : null;

回答by Shoe

Depending on your needs.

取决于您的需求。

// If not set, $cookie = NULL;
if (isset($_COOKIE['cookie'])) { $cookie = $_COOKIE['cookie']; }

or

或者

// If not set, $cookie = '';
$cookie = (isset($_COOKIE['cookie'])) ? $_COOKIE['cookie'] : '';

or

或者

// If not set, $cookie = false;
$cookie = (isset($_COOKIE['cookie'])) ? $_COOKIE['cookie'] : false;

References:

参考:

回答by Naftali aka Neal

Try this:

尝试这个:

 $cookie = isset($_COOKIE['cookie'])?$_COOKIE['cookie']:'';
 //checks if there is a cookie, if not then an empty string

回答by Mike Q

Example not mentioned in responses: Say you set a cookie for 60 seconds if conditions are right :

回复中未提及的示例:假设条件合适,您将 cookie 设置为 60 秒:

if ($some_condition == $met_condition) {
    setcookie('cookie', 'some_value', time()+ 60, "/","", false);
}

Technically we need to check that it's set AND it's not expired or it will throw warnings etc.. :

从技术上讲,我们需要检查它是否已设置且未过期,否则会引发警告等。:

$cookie = ''; //or null if you prefer
if (array_key_exists('cookie', $_COOKIE) && isset($_COOKIE['cookie'])) {
    $cookie = $_COOKIE['cookie'];
}

You would want to check in a way that ensures that expired cookies aren't used and it's set, the above example could obviously not always set the cookie etc.. We should always account for that. The array_key_exists is mainly their to keep warnings from showing up in logs but it would work without it.

您可能希望以一种确保不使用和设置过期 cookie 的方式进行检查,上面的示例显然不能总是设置 cookie 等。我们应该始终考虑到这一点。array_key_exists 主要是为了防止警告显示在日志中,但没有它也可以工作。