Search code examples
phpsessionsession-variables

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.


Solution

  • 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
    }