Pixelknight1398
Pixelknight1398

Reputation: 555

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.

Upvotes: 1

Views: 5376

Answers (1)

Pedro Lobito
Pedro Lobito

Reputation: 99081

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)

Upvotes: 2

Related Questions