Php session variable - is this statement true?

Hai folks,

is it true that session_start() should be called on the very first line of the php page even though the usage of the session variable may be in the middle of the page?

:rolleyes:

because i had a problem today that session varaiaible and solved after moving the session_start() to the first line.

before when problem exist :



ini_set('display_errors','1');
require_once("../../../includes/connection.php");
require_once("../../../includes/checkpoint.php");
require_once("../../../includes/set_time_zone.php");
require_once("../../../includes/session_start.php"); //see below for the content of this file
unset($empno);
$empno=$_SESSION['empno'];

content of session_start.php

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

then the problem solved after moving the session_start.php to the top

require_once("../../../includes/session_start.php");
ini_set('display_errors','1');
require_once("../../../includes/connection.php");
require_once("../../../includes/checkpoint.php");
require_once("../../../includes/set_time_zone.php");


unset($empno);
$empno=$_SESSION['empno'];

:rolleyes:

Yes, session_start(); must always be at the top of the page, but I don’t know why. I’ve searched for an answer to that but can’t find one.

:smiley: thank for the confirmation buddy.

I don’t think it literally has to be at the very top, you just need to ensure that you don’t output anything at all to the browser before you use session_start(). If even the slightest thing is sent to the browser before session_start() is used then you’ll get an error.

Yes, it doesn’t have to be at the very top but since session_start() sets a cookie (by default) then the same rule applies as with setcookie() - you can set cookies only before any output is sent to the browser because cookies are set in HTTP headers before any page content. And another more obvious reason - until you call session_start() you can’t really use $_SESSION so it’s most convenient to call it as soon as possible.

However, there’s a subtle limitation of using session_start() on every page - the browser can load only one page at a time so if someone has multiple browser windows or tabs open and tries to load any page from your site to all of them only one page will be downloaded by the browser - the other windows will wait until the first one finishes loading before proceeding. The blocking function is session_start() - it will block script execution when it detects another simultaneous request within the same session. It’s good to have it in mind in cases when you open some popup windows, load iframes or ajax requests which don’t really need to use the session - avoiding session_start() can speed up things for the user.