PHP Sessions

BEST PRACTICE: Always put session_start() at beginning of page, in top position (i.e. not inside conditional statements or functions). This is because it seems session variables aren't reachable, setting them overwrites the current value and calls session_start implicitly, and testing them would give unexpected results. So, ALWAYS call session_start() at the beginning of your script if you intent to use sessions.

Copy and test the below code on your server to see this for yourself.

$a = $_SESSION['count'];
$b = $_SESSION['count'];
echo "before session_start = " . $a . "<br />";  //echo's nothing;
echo "after session_start, before ++ = " . $b . "<br />";  //echo's the expected value;
if (empty($_SESSION['count'])) {
   $_SESSION['count'] = 1;
} else {
<p>Hello visitor, you have seen this page
    <?php echo $_SESSION['count']; ?>
<p>To continue, <a href="
    <?php echo $_SERVER['PHP_SELF']."?".htmlspecialchars(SID); ?>
    ">click here</a>.</p>

This behavior can be considered a BUG since if a session exists you shouldn't have to call session_start to use $_SESSION as expected.