Andeas Walz
Andeas Walz

Reputation: 1

If php $_SESSION variable has data

I am new to php. I am trying to check if the session variable has a value? If yes do nothing else set value. This is my code:

if (isset($_POST['ProductName'])) {
    if (!empty($_SESSION['UserBasketID'])) {
        $order = $_POST['ProductName'];
        $date = date("Ymd");
        $_SESSION['UserBasketID'] = $date.$order;
        var_dump($_SESSION['UserBasketID']);            
    } else {
        echo 'The session is set';
        if (isset($_SESSION['UserBasketID'])) {
            var_dump($_SESSION['UserBasketID']);
        }
    }
}

And can somebody tell me how it works in php.

Upvotes: 1

Views: 1053

Answers (2)

nickl-
nickl-

Reputation: 8731

The php documentation states that since 7.1.0:

session_start() now returns FALSE and no longer initializes $_SESSION when it failed to start the session.

So the correct way to check if the session property is set will now be:


if (session_start() && isset($_SESSION['UserBasketID'])) {
   // $_SESSION['UserBasketID'] is set
} else {
   // Either no session, $_SESSION not initialized or $_SESSION['UserBasketID'] not set
}

Upvotes: 0

M. Eriksson
M. Eriksson

Reputation: 13635

Your if-condition is backwards.

empty() returns true if the variable in not set or if it contains an empty value.
!empty() (with the ! in front of it) returns true if the variable is set and doesn't contain an empty value.

So the code:

if (!empty($_SESSION['UserBasketID']))

will evaluate as true if the session is defined and has a non-empty value, which means that you're currently only setting the session if it's already set.

Remove the ! in front of empty() and it should work:

if (isset($_POST['ProductName'])) {
    if (empty($_SESSION['UserBasketID'])) {
        $order = $_POST['ProductName'];
        $date  = date("Ymd");
        $_SESSION['UserBasketID'] = $date . $order;
        var_dump($_SESSION['UserBasketID']);            
    } else {
        echo 'The session is set';

        // We can remove the if-statement here since we
        // we've already checked it
        var_dump($_SESSION['UserBasketID']);
    }
}

Upvotes: 1

Related Questions