Differences

This shows you the differences between two versions of the page.

Link to this comparison view

computers:php_sessions [2008/06/11 04:28]
127.0.0.1 external edit
computers:php_sessions [2015/03/24 05:42]
Line 1: Line 1:
-====== 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. 
- 
-<code 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>​ 
- 
-</​code>​ 
- 
-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. 
-