沃梦达 / 编程问答 / php问题 / 正文

无法发送会话 cookie - 标头已发送

Cannot send session cookie - headers already sent(无法发送会话 cookie - 标头已发送)

本文介绍了无法发送会话 cookie - 标头已发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
已由 PHP 发送的标头

下面是我的 PHP 代码的一个简单示例(我希望如此)是不言自明的.我尝试做的是更新会话变量.但是脚本的输出如下:

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:

警告:session_start()[function.session-start]:无法发送会话 cookie - 标头已发送由(输出开始于/Library/WebServer/Documents/facebook/test.php:8)在/Library/WebServer/Documents/facebook/test.php在第 11 行

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

当然,警告是由第 8 行和第 9 行中的 echo 语句引起的.是否有任何简单的解决方案来阻止此警告.

The warning is caused by the echo statements in line 8 and 9, of course. Is there any simple solution to stop this warning.

感谢任何指点,安德烈

<?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();
?>

它很丑,虽然它首先缓冲输出......

It's ugly, while it buffers the output first...

推荐答案

输出开始后无法设置 cookie(或发送任何其他标头).您可以在第 1 行添加 ob_start() 来缓冲输出.

It's not possible to set cookies (or send any other headers) after output is started. You could add ob_start() at line 1 to buffer the output.

正确的解决方案是将逻辑与输出分开.检查例如http://www.paragoncorporation.com/ArticleDetail.aspx?ArticleID=21

The right solution is to separate logic from the output. Check out e.g. http://www.paragoncorporation.com/ArticleDetail.aspx?ArticleID=21

这篇关于无法发送会话 cookie - 标头已发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:无法发送会话 cookie - 标头已发送

基础教程推荐