1

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.

0

2 Answers 2

1

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']);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I just try out it and it rewrite my session variable by clicking on another item. Är du svensk?
@AndeasWalz - That's a totally different issue though. If this solves that specific issue in your question, you should accept it. If you got some other issue, then you should write a new question where you include a proper explanation and all the relevant code. And yes, jag är svensk :-)
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.