note 77734 added to ref.session

From: Date: Tue, 11 Sep 2007 09:36:28 +0000
Subject: note 77734 added to ref.session
Groups: php.notes 
Request: Send a blank email to php-notes+get-130354@lists.php.net to get a copy of this message
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. ---- Server IP: 209.41.74.194 Probable Submitter: 72.25.87.91 ---- Manual Page -- http://www.php.net/manual/en/ref.session.php Edit -- https://master.php.net/note/edit/77734 Del: integrated -- https://master.php.net/note/delete/77734/integrated Del: useless -- https://master.php.net/note/delete/77734/useless Del: bad code -- https://master.php.net/note/delete/77734/bad+code Del: spam -- https://master.php.net/note/delete/77734/spam Del: non-english -- https://master.php.net/note/delete/77734/non-english Del: in docs -- https://master.php.net/note/delete/77734/in+docs Del: other reasons-- https://master.php.net/note/delete/77734 Reject -- https://master.php.net/note/reject/77734 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#130354) next »