I have 2 different pages on the same website and same domain, one is responsible for the login on the website and set of the sessions, the second page is responsible for other tasks using the session established on the first page.
login.php
<?php
session_start();
ob_start();
//login checks and set of variables, for commodity lets use fixed values
$id = 10;
$name = "test";
//set of the sessions
$_SESSION['member_id'] = $id;
$_SESSION['member_name'] = $name;
session_write_close();
header("location: ../different_page.php");
?>
different_page.php
<?php
session_start();
ob_start();
//dumping session for test purpose and check whats inside
var_dump($_SESSION);
if(!isset($_SESSION['member_id'])) {
exit('ID not set');
}
echo $_SESSION['member_name'];
?>
The result of the different_page.php
array(0) { } ID not set
What could it be the issue? I have no idea at this point.
2
Answers
First, I think using session_start() in all the pages aren’t actually the best practice. You should consider starting session from the database connection file then use **require "[database connection file]" ** at all pages requiring the session.
You can try this suggestion
Your issue is that even though the two pages are on the same domain, you have a structure of this kind:
Due to the different folders, your app creates a session for each of your folders. You have two main types of solutions.
First. You could have a same
index.php
file at the same location that would respond to any requests and you would set up rewrite rules on your server to translate whatever request is supported into a request toindex.php
, allowing you to have a single session without worries. This is the approach I favor. In your example, yourdifferent_page.php
would be translated into anfolder2/index.php?req=different_page
which would, on its turn include/requiredifferent_page.php
.Second. You could use session-set-cookie-params to set the path of your request. Something like
I have never used this second approach, because it does not seem very intuitive to always check which path your request points to. It makes the code messy. So, I personally favor setting this inside the server with rewrite rules. A good those of the right regular expressions and a well-defined convention will remove this trouble for good.