1

I've read everywhere that in order for sessions to work properly, session_start must be called before outputting any html.

For example, this question: "Cannot send session cache limiter - headers already sent"

However, this example does not do that and it works:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
  <title>Counting with the SESSION array</title>
</head>
<body>
<FORM action="counter-session.php" method="GET">
<INPUT type="submit" name="Count" value="Count">
<?php
   session_start();
   if (! isset($_SESSION['counter']))
      $count = 0;
   else
      $count = $_SESSION['counter'];
   $count = $count + 1;
   $_SESSION['counter'] = $count;
   echo "count is $count";
?>
</FORM>

</body>
</html>

That is, the counter increments as expected. How come?

Addition question: is it true that once session_destroy is called, any further data stored into $_SESSION will not be saved (ie. further changes to $_SESSION will not be reflected the next time we use the $_SESSION variable from another page)?

Community
  • 1
  • 1
b_pcakes
  • 2,452
  • 3
  • 28
  • 45
  • check out your [output_buffering](http://php.net/manual/en/outcontrol.configuration.php#ini.output-buffering) ini setting. If it is set to something like `on` or an int value, then you can do this kind of mistakes... – Zimmi May 13 '16 at 21:45
  • By mistakes, I suppose you mean that this not the expected behavior? – b_pcakes May 13 '16 at 21:46
  • Should have quoted that word ;). By "mistakes" I mean effectively creating an output and then sending headers. Headers should be sent before html output. Output buffering is a setting that can be quite different (set or not set, and changing in size of the buffer) depending on server or hosting and you should not rely on it or set it explicitely. – Zimmi May 13 '16 at 21:51
  • So in this case, apparently no headers need to be send. The system uses exactly the same headers whether you start a session or not. – Mr Lister May 13 '16 at 21:54
  • 1
    Check this monster [answer](http://stackoverflow.com/a/8028987/4248472) and have a look at the *Output buffering as workaround* chapter – Zimmi May 13 '16 at 22:07

1 Answers1

1

I just tested it and the situation does come from output buffering.

If you want to check it, simply add ob_end_flush(); before starting your session.

Julie Pelletier
  • 1,740
  • 1
  • 10
  • 18