0

Premise: This was working completely fine on a MAMP local environment.

I have a classic setup to authenticate users by setting a session up after validating the information input in a form.

The files are 3: index.php --> Starts the session and checks if the session variable 'userId' exists. If it doesn't it shows a menu to login.

Register.js --> a file that contains js functions to signup and signin. Both functions use Fetch to post data to the php api endpoint

signin.php --? gets the posted information, checks if the username and password are correct and then creates session variables and echoes them back as a response.

The response comes through as expected to the fetch request (and i've validated it by passing the session variable to the response object and console.logging it on the index.php) but then when I refresh the page, the session variables are gone.

=====================

index.php starts the session right at the top of the page. EDIT: Added file below

<?php session_start();
  print_r($_SESSION); // This prints an empty array.
?>
<html>
  <head>
    <!-- Irrelevant -->
  </head>
  <body>
    <div id='main'>
      <div class='logo'>
      </div>
      <div class='searchContainer'>
        <!-- Irrelevant -->
      </div>
    <?php
    if (isset($_SESSION["userId"])){

    ?>
    <!-- Logged in menu --> 
      <div class=menuContainer>
        <!-- Irrelevant -->
      </div>
      <dialog class="nes-dialog is-rounded grrr-dialog" id="dialogAddRage">
        <!-- Irrelevant -->
      </dialog>
    <?php } else { ?>
    <!-- Logged out menu --> 
      <div class=menuContainer>
        <!-- Irrelevant -->
      </div>
      <dialog class="nes-dialog is-rounded grrr-dialog" id="dialogSignup">
        <!-- Irrelevant -->
      </dialog>
      <dialog class="nes-dialog is-rounded grrr-dialog" id="dialogSignin">
        <!-- Irrelevant -->
      </dialog>
    <?php } // else ?>
      <div align=center class="masonry-wrapper">
        <!-- Irrelevant -->
      </div>
      <div id="picModal" class="modal">
          <!-- Irrelevant -->
      </div>
      <section class="message-list">
        <!-- Irrelevant -->
      <section>
        <div id='footer'>
          <!-- Irrelevant -->
        </div>
      </section>
    </div> <!-- close main -->
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    <script src="js/dialog-polyfill.js"></script>
    <script src="js/jquery-3.4.1.min.js"></script>
    <script src="js/core.js"></script>
    <script src="js/register.js"></script>
    <script src="js/fetch_functions.js"></script>
    <script src="js/add_rage.js"></script>
  </body>  
</html>



register.js

$( "#signinForm" ).submit(function( event ) {
        event.preventDefault();
        //irrelevant for this question
        let myForm = document.getElementById('signinForm');
        let formData = new FormData(myForm);
        fetch('api/signin.php', {
          method: 'post',
          body: formData,
          credentials:"include"
        })
        .then(function(response) {
            if (response.status !== 200) {
              //irrelevant for this question
              return;
            }
            response.json().then(function(data) {
              console.log(data); //this prints data as expected
              window.location.reload();
            });
        })
        .catch(function(err) {
          //irrelevant for this question
          console.log(err);
        });
      });

signin.php

<?php
include_once 'db_connections.php';
$responseObj = new stdClass();
if (isset($_POST['name_field_signin'])){
    $userCheck = FALSE; //very simple query
    $sql = ("SELECT username, password, user_id FROM users");
    $result = $dbh->query($sql);
    while ($row = $result->fetch()){
        if ($_POST['name_field_signin'] == $row[ 'username'] && md5($_POST['password_field_signin']) == $row[ 'password'] ){
            $user_id = $row[ 'user_id'];
            $userCheck = TRUE;
            break;
        }
    }
    if ($userCheck){
        $_SESSION["userId"]=$user_id;
        $_SESSION["username"]=$_POST['name_field_signin'];
        $responseObj->status = 'signin-success';
        $responseObj->userId = $_SESSION["userId"];
    }
    else{
        $responseObj->status = 'signin-error';
    }
}
else{
    $responseObj->status = 'call-error';
}
$responseJSON = json_encode($responseObj);
echo $responseJSON;

Can this be related to the hosting? If so, shall I reconfigure any PHP variables in my script to store the sessions in a different way?

I've also tried a snippet from another stackoverflow answer (PHP Session not Saving) and it's returning that the folder is not writable.

However, I'd like to be sure this is the case and, eventually, change the configuration accordingly through code.

  • I don't see you calling [session_start()](https://www.php.net/manual/en/function.session-start.php). That might have something to do with it. Also, I would write a proof-of-concept that tests whether you can save something in a session and retrieve it. If that fails, check whether the [session save path()](https://www.php.net/manual/en/function.session-save-path.php) is writable by the PHP process. – kmoser Sep 08 '19 at 14:40
  • I call session_start() at the top of index.php as stated. How would you go about further testing session storage if that's pretty much what the file is already failing to do? – Thomas La Licata Sep 08 '19 at 17:04
  • You state that the script calls ``session_start()`` at the top but you aren't showing it. ``session_start()`` might be silently failing, perhaps because your script is inadvertently outputting whitespace or some other chars before you're calling ``session_start()``. Unless we can see your entire script, we'll never know. As for testing, I would write a standalone PHP script that calls ``session_start()`` and saves something in the session. Write another standalone script that calls ``session_start()`` and reads what's in the session. If that works, then sessions are not the issue. – kmoser Sep 08 '19 at 17:12
  • I've added the extract of the index without the irrelevant bits and pieces of html. I've also tested the session in another file and it does seem to get saved as expected, so I'm definitely missing something here. – Thomas La Licata Sep 08 '19 at 17:24
  • Also put `session_start()` at the start of `signin.php`. – Udo E. Sep 08 '19 at 23:45
  • That's was simple as that. I had issues with the fetch when calling multiple times the session_start and I read on another thread that the session would have been carried over when doing the request. Clearly it wasn't. – Thomas La Licata Sep 09 '19 at 16:20

0 Answers0