Search code examples
phpif-statementcookiesisset

PHP If (!isset(...) || !isset(...))


I'm trying to check if the first $_COOKIE['one'] exists OR the second $_COOKIE['two'] exists and if none exists to redirect the user.

Only one of those two cookies are going to exist when this script is running.

if (!isset($_COOKIE['one']) || !isset($_COOKIE['two'])) {
    header('Location: ./');
} else {
    ...
}

I tried many things but every time I get into this if altough one of those cookies always exist.


Solution

  • This is a simple case of inverted logic. As Mark pointed out, you need to be using the boolean && (AND) operator. You are trying to see if both don't exist, then send the header. Currently, if either exists, you send the header anyway.

    Just change if (!isset($_COOKIE['one']) || !isset($_COOKIE['two'])) {

    to

    if (!isset($_COOKIE['one']) && !isset($_COOKIE['two'])) {

    Or (||) returns true if either the left or right of the statement is true. And (&&) returns true only if both parts of the statement are true. The Not(!) operator reverses true->false and false-> true.

    isset tells you if the cookie exists. If the cookie exists, it returns true. You are correct in using not on this, as you want it to tell you if the cookie doesn't exist (opposite). However, you only want to send the header if BOTH cookies don't exist. Or will send it if one doesn't exist.