2016-04-30 56 views
1

我有一些代码:检查Cookie是否为空或在php中设置无效?

<?php 
    $cookiename1 = "uservalue"; 
    $cookie1 = (string)$_COOKIE[$cookiename1]; 
    if($cookie1 != ""){ 
     echo "<span style = 'color: white'>". $cookie1 . "</span>"; 
    } 
    else{ 
     die("Could not get profile"); 
    } 
?> 

这是为了检测一个cookie是空的或没有,但如果cookie等于“”然后运行它的回声声明。

我本来有:

<?php 
    $cookiename1 = "uservalue"; 
    $cookie1 = $_COOKIE[$cookiename1]; 
    if(isset($cookie1) && !empty($cookie1)){ 
     echo "<span style = 'color: white'>". $cookie1 . "</span>"; 
    } 
    else{ 
     die("Could not get profile"); 
    } 
?> 

,但我得到了相同的结果。不知道我在这里做错了什么= /如果有人可以帮助这将是很棒的。

+0

该cookie存在,但它是空的... –

+0

是的这是正确的。我正在检查它是否为空,并且因为它应该死掉(“无法获取配置文件”),而是运行echo语句。 – Pixelknight1398

回答

2

您需要使用setcookie()

例子:

setcookie("uservalue", "some-value", time()+3600, "/", "example.com", 1); 

设置cookie后,您可以检查它是否是空的:

if (!empty($_COOKIE["uservalue"])){ 
    echo "<span style='color: white'> cookie isn't empty </span>"; 
} 

emptytrue在以下条件下:

"" (an empty string) 
0 (0 as an integer) 
0.0 (0 as a float) 
"0" (0 as a string) 
NULL 
FALSE 
array() (an empty array) 
var $var; (a variable declared, but without a value in a class) 
+0

那么这个cookie已经存在于浏览器中,并且它被设置为一个空字符串。如果你没有注意到,我已经检查了第二块代码中的isset和!空白,它返回了与第一块相同的结果。 – Pixelknight1398

+0

做一个'var_dump($ _ COOKIE [“uservalue”])'你看到了什么? –

+0

我看到字符串(2)“”“” – Pixelknight1398