【发布时间】:2020-03-31 04:04:17
【问题描述】:
我收到此错误:
第 35 行的脚本“/home/path/to/file/php”中发生错误:无法修改标头信息 - 标头已发送(输出开始于 /home/path/to/file/to/header. html:7)
我知道我在尝试设置 cookie 时遇到错误,并且我知道 setcookie 在它之前不能有任何输出...问题就在那里,我必须为数据库添加包含文件文件的连接和重定向。所以我在包含文件之后添加了 setcookie 。我也尝试将 setcookie 放在包含文件上方,但它也没有帮助。
我的代码
<?php # Script 2.5 - main.inc.php 2 3
// Redirect if this page was accessed directly:
if (!defined('BASE_URL')) {
// Need the BASE_URL, defined in the config file:
require('../includes/config.inc.php');
// Redirect to the index page:
$url = BASE_URL . 'index.php?p=vote';
header ("Location: $url");
exit;
}
$vote = new Vote;
//get vote and options data
$voteData = $vote->getVotes();
//if vote is submitted
if(isset($_POST['voteSubmit'])){
$votesData = array(
'vote_id' => $_POST['voteID'],
'vote_option_id' => $_POST['voteOpt']
);
//insert vote data
$voteSubmit = $vote->vote($votesData);
if($voteSubmit){
//store in $_COOKIE to signify the user has voted
setcookie($_POST['voteID'], 1, time()+60*60*24*365); //Error Occurs here
$statusMsg = 'Your vote has been submitted successfully.';
}else{
$statusMsg = 'You cannot vote more than once.';
}
}
?>
//The html form code goes here
我也试过了
setcookie($_POST['voteID'], 1, time()+60*60*24*365, '\');
和
setcookie($_POST['voteID'], 1, time()+60*60*24*365, '\', domainName);
但是这些也没有解决我的问题。
我还创建了一个名为 test.php 的新文件并测试了以下代码。
<?php
$cookie = 'test';
$cookie_name = "cookieName";
$cookie_value = $cookie;
setcookie($cookie_name, $cookie_value, time() + (86400 * 365));
if((isset($_COOKIE[$cookie_name])) && ($_COOKIE[$cookie_name] != "")) {
echo 'yes';
}
else{
echo 'no';
}
phpinfo();
?>
它打印 yes
当我在我的主 php 文件中尝试使用相同的代码时,它会显示错误并打印是。我不知道我的代码有什么问题。
我也尝试过谷歌搜索,但没有成功。
【问题讨论】:
-
读取错误,它说输出开始于
/home/path/to/file/to/header.html。输出内容后不能设置headers或cookies,需要更改代码结构。 -
请检查live server的php版本,有低版本请更新
-
@PHPGeek PHP 版本会如何影响这个错误,特别是?从您的评论中不清楚。如果您对此有所了解,请解释为什么这是一个问题。然后我们都可以从中学习。还是只是猜测?
-
@SushankPokharel 您可以在 php.ini 中使用 output_buffering。由于上面已经发送了标头,因此您需要在将输出发送到客户端之前保留输出。
-
@ADyson 谢谢你的链接。您的链接还包含更多内容,但输出缓冲解决了我的问题。我将看一下并了解有关输出缓冲的更多信息。
标签: php cookies http-headers