title: Cannot send session cookie - headers already sent
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/8028957/headers-already-sent-by-php">Headers already sent by PHP</a>  </p>
  </blockquote>
  
  
  
  <p>Below is a simple example of my PHP code which (I hope so) is self explanatory. What I try to do is to update the session variable. But the output of the script is as follows:</p>
  
  <blockquote>
    <p>Warning: session_start()
    [function.session-start]: Cannot send
    session cookie - headers already sent
    by (output started at
    /Library/WebServer/Documents/facebook/test.php:8)
    in
    /Library/WebServer/Documents/facebook/test.php
    on line 11</p>
  </blockquote>
  
  <p>The warning is caused by the <code>echo</code> statements in line 8 and 9, of course. Is there any simple solution to stop this warning.</p>
  
  <p>Thanks for any pointers, Andrej</p>
  
  <pre><code>&lt;?php
  session_start();
  $_SESSION['percent'] = 0;
  $iterations = 50;
  
  for ($i = 0; $i &lt;= iterations; $i++) {
    $percent = ($i / $iterations) * 100;
    echo "Hello World!";
    echo "&lt;br /&gt;";
    // update session variable
    session_start();
    $_SESSION['percent'] = number_format($percent, 0, '', '');
    session_commit();
  }
  ?&gt;
  </code></pre>
  
  <p>The only solution that works (i.e. updates the session variable) for me is:</p>
  
  <pre><code>&lt;?php
  ob_start();
  session_start();
  $_SESSION['percent'] = 0;
  $iterations = 50;
  
  for ($i = 0; $i &lt;= 50; $i++) {
    $percent = ($i / $iterations) * 100;
    echo "Hello World!";
    echo "&lt;br /&gt;";
    // update session variable
    session_start();
    $_SESSION['percent'] = number_format($percent, 0, '', '');
    session_commit();
  }
  ob_flush();
  ?&gt;
  </code></pre>
  
  <p>It's ugly, while it buffers the output first...</p>