Cannot send session cookie - headers already sent(无法发送会话 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 - 标头已发送
基础教程推荐
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01