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?