skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. Your issue is that even though the two pages are on the same domain, you have a structure of this kind:

    folder1
        different_page.php
        folder2
            login.php
    

    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 to index.php, allowing you to have a single session without worries. This is the approach I favor. In your example, your different_page.php would be translated into an folder2/index.php?req=different_page which would, on its turn include/require different_page.php.

    Second. You could use session-set-cookie-params to set the path of your request. Something like

    $nrOfHours = 4;
    session_set_cookie_params(60*60*$nrOfHours, "/folder2");
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search