I have trouble accessing my session variable from one page to another. When I access the response from the page that sets the session variable as a regular JSON response, I can confirm that the session variable is being set as desired. However, when I navigate to another page using location.replace, I use PHP sessionstart() and cannot access the session variables. I get an empty array for $_SESSION, and no value is printed out when the session variable is echoed. I have attached the code for the page that sets the session variable and the page trying to access it. Additionally, I am trying to run the code on an Apache server and access the pages from the exact same domain with all files in the same location.
I have tried following all the PHP rules for session variables I found online, including adding to the first page, which sets the variable
session_write_close();
And expect that the session variable set is echoed/accessed on the second page.
First Page that sets the session variable:
<?php
session_start(); // Start the session
$_SESSION['display_page2'] = "true";
echo "The value of 'display_page2' is: " . $_SESSION['display_page2'];
?>
Second Page that is meant to access the session variable:
<?php
session_start();
var_dump($_SESSION); // Check the contents of the session array
echo "The value of 'display_page2' is: " . $_SESSION['display_page2'];
?>
AJAX request on third page that calls the first page to set the session variable and redirects to the second page (in the response I am able to verify that the session variable is being set as desired):
$.ajax({
type: "POST",
url: "https://url-to-api",
dataType: "json",
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function() {
$.ajax({
type: "POST",
url: "firstpage.php",
data: { display_page2: true },
success: function(response) {
alert(response);
location.replace("secondpage.php");
},
error: function() {
alert("Unsuccessful");
}
});
},
error: function() {
alert("Unsuccessful. Please try password again or request new password.");
location.reload();
},
});