note 77734 deleted from ref.session by nlopess
| From: | nlopess@php.net | Date: | Tue, 11 Sep 2007 10:50:39 +0000 |
| Subject: | note 77734 deleted from ref.session by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-130366@lists.php.net to get a copy of this message | ||
Note Submitter: daniel at nohair dot com
----
As recommended by http://nohair.com/code/computers: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.
<?php
$a = $_SESSION['count'];
session_start();
$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 {
$_SESSION['count']++;
}
?>
<p>Hello visitor, you have seen this page
<?php echo $_SESSION['count']; ?>
times.</p>
<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.