简体   繁体   中英

Checking if Cookie is empty or set in php not working?

I have some code:

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

which is supposed to detect if a cookie is empty or not but when the cookie is equal to "" then it runs the echo statement.

I originally had:

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

But i get the same result. Not sure what im doing wrong here =/ If anyone could help that would be awesome.

You need to use setcookie()

Example:

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

After setting the cookie, you can check if it's empty:

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

empty is true on the following conditions:

"" (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)

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