如果没有设置cookie,我想回复cookie是空的

时间:2017-08-07 16:52:29

标签: php cookies

检查是否有饼干

$d=0;
//**data is stored in cookies as arrays**
if(is_array($_COOKIE['data']) {
    //**data increment by 1 if found**
    $d=$d+1;
}
//**if data not found echo data not found**
if($d==0) {
    echo "data is not present";
}
else{
    echo "data presrnt";
}

我注意到未定义的变量数据

2 个答案:

答案 0 :(得分:0)

使用isset检查变量集:

$d=0;
//**data is stored in cookies as arrays**
if(isset($_COOKIE['data']))
    if(is_array($_COOKIE['data']){
    //**data increment by 1 if found**
        $d=$d+1;
    }
//**if data not found echo data not found**
if($d==0){
echo "data is not present";
}
else{
echo "data presrnt";
}

答案 1 :(得分:0)

您可以使用$_GET函数检查变量是否存在,如下所示:

isset()

您还可以使用if(isset($_COOKIE['data']) && is_array($_COOKIE['data']){ echo "data present"; } else{ echo "data is not present"; } 函数检查变量是否存在而不是空,如下所示:

empty()

空值为:if(!empty($_COOKIE['data']) && is_array($_COOKIE['data']){ echo "data present and it's not empty"; } else{ echo "data is not present"; }

我也看到你在cookie中存储一个数组,我建议在存储到这样的cookie之前序列化数组的最佳实践:

null, "", 0, "0", 0.0, false, [], $var// undeclared var

获得它的价值所有你需要做的是:

setcookie('data', serialize($data), time()+3600);