gpt4 book ai didi

php - 警告 : Cannot modify header information - headers already sent by ERROR

转载 作者:IT老高 更新时间:2023-10-28 11:55:13 25 4
gpt4 key购买 nike

我一直在为这个错误苦苦挣扎。

一开始,我只是认为这是空白,但经过进一步研究,我认为它可能是类似这样的问题:

Look for any statements that could send output to the user before this header statement. If you find one or more, change your code to move the header statement before them. Complex conditional statements may complicate the issue, but they may also help solve the problem. Consider a conditional expression at the top of the PHP script that determines the header value as early as possible and sets it there.

我猜测包含 header 与 header() 一起导致了问题,但我不确定如何重新排列代码以消除此错误。

如何消除错误?

<?php
$username = $password = $token = $fName = "";

include_once 'header.php';

if (isset($_POST['username']) && isset($_POST['password']))
$username = sanitizeString($_POST['username']);

$password = sanitizeString($_POST['password']); //Set temporary username and password variables
$token = md5("$password"); //Encrypt temporary password

if ($username != 'admin')
{
header("Location:summary.php");
}
elseif($username == 'admin')
{
header("Location:admin.php");
}
elseif($username == '')
{
header("Location:index.php");
}
else
die ("<body><div class='container'><p class='error'>Invalid username or password.</p></div></body>");

if ($username == "" || $token == "")
{
echo "<body><div class='container'><p class='error'>Please enter your username and password</p></div></body>";
}
else
{
$query = "SELECT * FROM members WHERE username='$username'AND password = '$token'"; //Look in table for username entered
$result = mysql_query($query);
if (!$result)
die ("Database access failed: " . mysql_error());
elseif (mysql_num_rows($result) > 0)
{
$row = mysql_fetch_row($result);
$_SESSION['username'] = $username; //Set session variables
$_SESSION['password'] = $token;

$fName = $row[0];
}
}
?>

最佳答案

长期的答案是 PHP 脚本的所有输出都应该缓冲在变量中。这包括标题和正文输出。然后在您的脚本结束时执行您需要的任何输出。

快速解决您的问题的方法是添加

ob_start();

作为脚本中的第一件事,如果您只在这个脚本中需要它。如果您在所有脚本中都需要它,请将其作为 header.php 文件中的第一件事添加。

这将打开 PHP 的输出缓冲功能。在 PHP 中,当您输出某些内容(执行回显或打印)时,它必须在那时发送 HTTP header 。如果您打开输出缓冲,您可以在脚本中输出,但 PHP 在刷新缓冲区之前不必发送 header 。如果您打开它并且不关闭它,PHP 将在脚本完成运行后自动刷新缓冲区中的所有内容。几乎在所有情况下都将其打开并没有什么坏处,并且可以在某些配置下为您带来小幅性能提升。

如果您有权更改您的 php.ini 配置文件,您可以找到并更改或添加以下内容

output_buffering = On

这将关闭输出缓冲,而无需调用 ob_start()。

要了解有关输出缓冲的更多信息,请查看 http://php.net/manual/en/book.outcontrol.php

关于php - 警告 : Cannot modify header information - headers already sent by ERROR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9707693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com