Cannot send cookie session - headers already sent

Possible Duplicate:
Headers Already Submitted by PHP

Below is a simple example of my PHP code, which (I hope) explains itself. I am trying to update a session variable. But the script output looks like this:

Warning: session_start () [function.session-start]: Cannot send session cookie - headers have already been sent (the output started with /Library/WebServer/Documents/facebook/test.php:8) in / Library / WebServer / Documents / facebook / test.php on line 11

The warning is triggered by operations echoon lines 8 and 9, of course. Is there a simple solution to stop this warning.

Thanks for any pointers, Andrew

<?php
session_start();
$_SESSION['percent'] = 0;
$iterations = 50;

for ($i = 0; $i <= iterations; $i++) {
  $percent = ($i / $iterations) * 100;
  echo "Hello World!";
  echo "<br />";
  // update session variable
  session_start();
  $_SESSION['percent'] = number_format($percent, 0, '', '');
  session_commit();
}
?>

The only solution that works (i.e. updates the session variable) for me is:

<?php
ob_start();
session_start();
$_SESSION['percent'] = 0;
$iterations = 50;

for ($i = 0; $i <= 50; $i++) {
  $percent = ($i / $iterations) * 100;
  echo "Hello World!";
  echo "<br />";
  // update session variable
  session_start();
  $_SESSION['percent'] = number_format($percent, 0, '', '');
  session_commit();
}
ob_flush();
?>

, ...

+3
5
+2

session_start() for.

session_commit() for .

script.

+4

previeus session-start(), .php ansi utf-8 BOM . bc .

+2

session_start() . .

session_commit() , PHP .

+1
source

As others have argued, the cause of the error is the second session_start()one you are using. However, the actual reason it causes the error is because you are trying to set the header after you have already sent the output. Since the session_start () function sets the session cookie, it tried to set the header of the cookie, which is already after the echo content.

+1
source

Source: https://habr.com/ru/post/1781931/


All Articles