0

After combing through SO and trying the approved suggestions found here, my related problem persists. My page starts with a simple login and then you navigate to other potential pages through drop down menus. When I redirect from the index page to a welcome page, I can recall values from my $_SESSION array on to the welcome page. The problem is when you navigate to another page after after that point. The content of the $_SESSION array gets erased. Even if I reload the same page that already has a return from the $_SESSION array, the array gets erased.

I use XAMPP OSX, php 7.9.2 and localhost on my own computer. I've restarted XAMPP. I've emptied cache and restarted my browser. I've tried other browsers. I've rebooted my computer.

Is there something I can do with my server settings? What could be the source of my problem?

What is very strange is that the issue came out of the blue. I was able to preserve $_SESSION with no problems weeks before and all of a sudden it began to drop its values.

Update 1

So I've made some changes to my code below to have a separate AJAX page and php pages to really clarify what I'm doing. The problem seems to have improved with what I did. HOWEVER, there still remains some mysteries:

1) On log out, I get a warning from my AJAX output that the SESSION variable doesn't exist. This is strange as I am able to print out my session content from my php pages when I've logged in and I navigate to other pages.

2) I am unable to make a simple function call (an alert popup) when my footer loads for every page. This alert popup is on the same page as AJAX functions (which seem to work), but the popup doesn't pop.

Header

<?php session_start() ?>

<!DOCTYPE html>
<html lang="en">
     <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">    
        <meta name="author" content="">
        <link rel="icon" href="../../favicon.ico">

        <title>test site</title>

        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet "href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

</head>
<body>

    <div class="row">
        <div class="container col-xs-12" id="OPheader">
            <div id="logoText">
                <p>
                    Test Pages
                </p>
            </div>

Navigation Menus


<div class="btn-group menuButton ">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        So what you wanna do?&nbsp; &nbsp;  <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" id="daMenu">
        <li><a href="testHomePage.php">Continue procrastination</a></li>
    </ul>
</div>
<!-- ============  user personal menu ====== -->
<div class="btn-group userMenuButton ">
  <button type="button" class="btn btn-default dropdown-toggle" id="userMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
     <label id="user-name-icon" >Your name</label>
   <!--  Insert user name from database here -->
     <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" id="daUserMenu">
    <li><a href="testOtherPage.php">Order another pizza</a></li>
    <li role="separator" class="divider"></li>
    <li><a onclick="javascript: killSession();" >Log Out</a></li>
  </ul>
</div>

Index page

<?php include("testHeader.php"); ?>
<?php include("testIndexTools.php"); ?>


      </div>
    </div>

<!-- 
    ======================    Login  Fields ======================================
 -->


    <div class="container">
      <div class="row">
        <div class="col-md-4 col-md-offset-4">
          <div class="well" id="loginBox">
            <div>
              <div id="loginErrorMsg" ></div>
                <form method="POST" action="">
                  <div class="enterBox">User: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<input type="text" name="user_name" placeholder="uh... who?" >
                  </div>
                  <br>
                  <div class="enterBox">Password: <input type="text" name="user_pw" placeholder="Don't mess this up" >
                  </div>
                  <br>
                  <div >
                    <input class="btn btn-primary submitText" type="submit" name="login_submit" value="Submit your soul">
                </div>
                </form>
            </div>
          </div>
        </div>
      </div>

    </div>


<script type="text/javascript">
  var error = "Login unsuccessful. Please re-enter credentials.";
  var disp = document.getElementById('loginErrorMsg');
  function showError(){
    disp.innerHTML = error;
  }
</script>
<?php include("testFooter.php"); ?>
</body>
</html>

PHP Tools for Index page

<?php

$errors = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    list($errors) = validate_form(); // check for blank input fields
    if ($errors) { // If validate_form() returns errors,
        show_errors($errors);           // show error messages          

    }   else { 

        process_form(); 
    }
}   



//  on succesful login, this function is called to redirect page
function process_form(){
    session_start();
        $_SESSION['logged_user'] = htmlentities($_POST['user_name']); 


        if (isset($_SESSION['logged_user'])){
            session_regenerate_id(true);
            header("Location: /OPsite/SOmock/testHomePage.php");
            exit();
        }   else {
            echo "Session wasn't set so not redirecrting";
            exit();
        }   

} 

function show_errors($errors){
    echo  '<script type="text/javascript"> showError(); </script>';
}

// validate your data
function validate_form(){
        $errors = array();
        $userCu = trim($_POST['user_name'] ?? ''); 
        $userPw = trim($_POST['user_pw'] ?? '');

        if (strlen($userCu) == 0){
            $errors[] = "Please enter name";
                return $errors;
        } else if (strlen($userPw) == 0) {
            $errors[] = "Please enter password";
                return $errors;
        }
}
?>

Welcome page

<?php include("testHeader.php"); ?>
<?php include("testMenu-bar.php"); ?>
<?php include("testWelcomePageTools.php"); ?>


    </div>
</div>

 <!-- ================================= welcome Page =============== -->
<div class="row" id="homePage">
     <div class="container ">
        <h1> Stop procrastinating and get back to work</h1><br>
    </div>



</div>

<?php include("testFooter.php") ?>
</body>
</html>

PHP tools for Welcome Page

<?php

// AJAX call to set name from HomePage
if (isset($_POST['sessName'])){
    // $_SESSION['logged_user'] = htmlentities($_POST['user_name']); // user-icon name set here

    $userName = $_SESSION['logged_user'];
    // echo $_SESSION['logged_user'];
    echo "Session data exists<br>";
    echo $userName;
    // print_r($_SESSION); // when homePage loads, this is to check array
    // echo "sessName";
} else {
    $noSession = "No session data<br>";
    echo $noSession;
    print_r($_SESSION);
}
?>

other page to navigate to


<?php include("testHeader.php"); ?>
<?php include("testMenu-bar.php"); ?>

<?php

echo "this is the testSession Page<br>";
print_r($_SESSION);
?>

<?php include("testFooter.php") ?>
</body>
</html>

Footer


<script type="text/javascript" src="testFooterJS.js">baba();</script>

<!-- === log out behavoiur ============== -->
<?php
// AJAX call to kill session
if (isset($_POST['killSess'])){

  unset($_SESSION['logged_user']);

  session_destroy();
  $_SESSION = array(); 

  exit();
}
?>

javascript/AJAX page for logging in/out


//====== AJAX log in behaviour ========== 


function sessionName(){
  alert("name calling");
        $.ajax({
            type: 'post', 
            url: 'testHomePageTools.php',
            data:'sessName', // in PHP page, this will correspond with: $_POST['action'] == 'fillMenu' 
            dataType: 'text',
            success: function (data) {  
              alert("Your name" +data);
                var userName = data;
                    var icon = document.getElementById('user-name-icon');
                  icon.innerHTML = "You are logged in as: " + userName;
            alert("You are logged in as: " + userName);
            }, 
            error: function(data){
              alert("something's gone wrong on entry");
              console.log(data);
              // alert(data);
          }
        });
};  




//====== AJAX log out behaviour ========== 

  function killSession(){
        $.ajax({
            type: 'post', 
            url: 'testFooter.php',
            data:'killSess', // in PHP page, this will correspond with: $_POST['action'] == 'fillMenu' 
            dataType: 'text',
            success: function (data) {  

              console.log(data);
                alert("Bye bye");
                     window.location = "http://localhost/OPsite/SOmock/testIndex.php";

            }, 
            error: function(data){
              alert("something's gone wrong on exit");
              console.log(data);
              // alert(data);
          }
        });
};  

// =============  test to see if footer loads ===========
function baba(){
  alert("footer loaded");
};
codeWalrus
  • 23
  • 4
  • 4
    `var unsetSession = "";` - That destroys the session and the return value (nothing) becomes the javascript variable unsetSession. The session_destroy will not be called conditionally. You might try creating an endpoint which unsets the session instead. – James Dec 11 '19 at 21:00
  • @James: how about ""; Would this preserve my $_SESSION values? – codeWalrus Dec 11 '19 at 21:54
  • 1
    No, you can't do things in php conditionally on events in Javascript without making a HTTP request of some kind. – James Dec 12 '19 at 18:08
  • @James: So would it be better to test for conditions and close my session on a php page but have this triggered via AJAX? – codeWalrus Dec 13 '19 at 13:59
  • If you want to do it by AJAX that will be fine, you could also do it by going to a URL that logs the user out. Bottom line is, all that happens on the server, so you need to trigger a visit to the server by some user action. – James Dec 13 '19 at 17:54
  • @James So I've made some changes to my code (see above) and separated out my AJAX calls. Thanks for the advice, it seemed to have improved something. However, still buggy (see above updated text) – codeWalrus Dec 16 '19 at 14:02

1 Answers1

1

I figured out my problem. After my code updated as posted, I discovered that my problem was that I thought that having session_start() on my header would address and cover all the pages that included the header. This is not the case. The session_start() has to be on literally every php page that refers to $_SESSION super global. This was not very clear on my research, but through trial and error I figured it out.

Thanks

codeWalrus
  • 23
  • 4
  • FYI, it's extremely common to have a "header file" that you `require_once()` at the top of every page, and this is used to include necessary preamble code such as this. – Mike Robinson Dec 18 '19 at 16:00