0

I have a top navigation bar that is inside an external PHP file that is just linked in place on the main page by include "topnav.php"; that way when I needed to change the href="" I don't need to go through every page. I also use that to display -> Logged in as: lastname, firstname. I achieved that by using the session ID and use it to a select query to get the lastname and firstname of the user.

The problem comes in the main page since I also need the session there since I need the user ID in queries.

If I have the session_start() on both files the error: PHP Sessions has already started shows, but when I remove the session_start() on the topnav.php file it shows : unidentified variable _SESSION ...

Is there another alternatives to achieve what I want?

RFA
  • 771
  • 1
  • 5
  • 14
  • sounds like the topnav file is included before session_start() is called in the main script. To my opinion session_start() should be called in the main script (or in an include file that only acts as a kind of config file). Not in every single included file. Because, what if session is needed in the footer, or in the menu etc – Ivo P Jul 18 '17 at 07:35
  • @Ivo P I actually did that, but if I only include it on the main page, the topnav.php will give an error that says unidentified variable _SESSION ... I need the session on the topnav.php file. – RFA Jul 18 '17 at 08:00
  • if that happens, it sounds to me like session_start() was not yes called before the include was done – Ivo P Jul 18 '17 at 08:19

1 Answers1

0
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

Start it, if it hasn't started.

Keep it in the main file, in the inner file, start it if it hasn't been started.

For versions of PHP < 5.4.0

if(session_id() == '') {
   session_start();
}

via Check if PHP session has already started

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78