1

I have a simple fetch request that looks like this:

JavaScript (React)

fetch('/includes/signon.php', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    Email: event.target.form.email.value,
    Password: event.target.form.password.value,
  })
})
.then((response) => {
  return response.text()
}).then((body) => {
  this.displayWelcomeMessage(body);
})

And on the backend, I have PHP that handles the fetch request like so:

PHP 5

<?php
require_once('database.php');
session_start();

$request_body = file_get_contents('php://input');
$json = json_decode($request_body);

if (!empty($json->Email) && !empty($json->Password)) {
  global $db, $json;
  $sql = "SELECT `user_id` from users where email = ? AND password = ?;";
  $stmt = $db->initialize_statement();
  if (!$stmt->prepare($sql)) {
    $error = $stmt->error;
    echo $stmt->error;
  } else {
    $email = $json->Email;
    $password = $json->Password; // Stored as a string for the sake of simplicity
    $stmt->bind_param('ss', $email, $password);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($result);
    while($stmt->fetch()) {
      if ($stmt->num_rows === 0) {
        echo "Incorrect Username or Password";
      } else {
        // Here lies the problem...
        $_SESSION['user_id'] = $result;
        echo "Welcome, User #".$result."!";
      }
    }
    $stmt->close();
  }
} else {
  var_dump($_SESSION); // For debugging purposes only
}

Now, here's the problem! The body of the response displays "Welcome, User #12!" when I log in like it should, but $_SESSION['user_id'] is set to 12 without being stored in the actual session...

If I make a GET request to the page, it dumps the $_SESSION out and $_SESSION['user_id'] is nowhere to be found.

Why? What am I doing wrong? I just want to finish this project...

UPDATE: The var_dump($_SESSION); at the bottom of the page is dumping a different session than the $_SESSION that I'm using to store "user_id". I wonder what is causing this? Why would it dump a different session than the one I'm storing variables in?

session_id() on session I'm storing to: 0q44kc1fkph8fkc8gt35gfabe6

session_id() on session I'm dumping: a493j3v5vbnlon02s1s7bpkqj3

So... It's creating a new session every time I set "user_id"? Why?

ihodonald
  • 745
  • 1
  • 12
  • 27

1 Answers1

1

The issue most likely lies in the fact that you have cookies enabled for sessions, and the cookie lifetime is 0. For example, let's try making it 7 days instead at the beginning of your script:

ini_set('session.cookie_lifetime', 60 * 60 * 24 * 7);

If this works, I would recommend moving the session.cookie_lifetime setting to your php.ini file so each script you write does not require running ini_set().

For more information: https://stackoverflow.com/a/9797962/823549

1000Nettles
  • 2,314
  • 3
  • 22
  • 31
  • I tried this and it didn't work. For some reason, I'm looking in my php.ini file and inside the directory found at session.save_path and I'm finding that it's creating two files **and one is empty.** I wonder if that could be the issue. – ihodonald Feb 17 '18 at 05:07
  • Thank you for the suggestion though! – ihodonald Feb 17 '18 at 05:47
  • 1
    No problem. I have a feeling this may be because you are posting via React to your endpoint, the session is getting created, but not then attributed to the actual frontend. – 1000Nettles Feb 17 '18 at 18:39
  • ^ I think you're right about that. I'm looking into the PHP docs right now (specifically here:[www.php.net/manual/en/session.configuration.php) to see if I can figure out a way to get my script to keep track of the session ID (possibly storing it in the database or something). – ihodonald Feb 17 '18 at 23:17
  • 1
    I wonder if when the session starts and it assigns a cookie, you need to actually receive that cookie in React and assign it to the user's browser? – 1000Nettles Feb 17 '18 at 23:18
  • 1
    Like as in JavaScript localStorage or something along those lines? docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage – ihodonald Feb 17 '18 at 23:19
  • I haven't used much ReactJS before, but potentially https://www.npmjs.com/package/react-cookie? – 1000Nettles Feb 17 '18 at 23:23
  • 1
    Ooh... I will look into react-cookie. I'm not set up to do development right now though... I will have to get back to you when I get it running. – ihodonald Feb 17 '18 at 23:28
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/165348/discussion-between-1000nettles-and-ihodonald). – 1000Nettles Feb 17 '18 at 23:29