Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php session_start with include files

Tags:

php

session

i learned a lot about session start from my previous question. Now i'm wondering how session locking occurs when files are included in other files. Lets say i have:

page.php

include('header.php');
...some html content....
include('sub_page.php');
...more html....

header.php:

session_start();
..save session vars...
..print web page header...

sub_page.php

session_start();
...use session vars....
..print page content...

When i open page.php, does the session become unlocked as soon as header.php is done? or is it live for the whole page.php life, so sub_page's session is blocked? Is the session_start in sub_page necessary? Would it be better practice if I session_write_close every time i'm done with session data? (Though that would mean session_starting everytime i'd like to use a session variable).

like image 633
Andrea Avatar asked Aug 02 '11 15:08

Andrea


2 Answers

  1. You should start session only one time. In your example, just need session_start() at the first line of page.php
  2. session_start() will generate E_NOTICE if session was previously started. You can use @session_start() to ignore it.
  3. It also generates E_NOTICE if you use session_start() after you output HTML code.
like image 179
sonnb Avatar answered Oct 15 '22 05:10

sonnb


Due to the answers above talking about errors if session already started, I just wanted to point out you can do:

if (!isset($_SESSION))
  {
    session_start();
  }

Then if the $_SESSION is already started (set) it wont perform the start function.

Although there's nothing better than a well structured file and folder layout with a good framework setup. Even if just a simple framework structure which separates business logic from presentation.

This way, you'd have something similar to a config folder with initialisation scripts, or at the very least have include files in some folder which are included in all pages/scripts.

Then you simply have your session_start() in (depending on your setup) either the very first include file, or in a separate include file and then include that session file when needed in a specific area of the script.

Either way, you then don't need to call it in any other files, as you know it's simply not required based on your design structure.

If you do not have a file which is always included, then at least use the isset() check.

like image 27
James Avatar answered Oct 15 '22 03:10

James