RFA
RFA

Reputation: 851

Session_start on included php file conflicting with session_start on main page

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?

Upvotes: 0

Views: 154

Answers (1)

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

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

Upvotes: 0

Related Questions