我不确定为什么这段代码会抛出已发送的标头。我看过: How to fix "Headers already sent" error in PHP
我仍然得到错误。它是用ANSI编码的,我用notepad ++键入它,似乎没有空格......任何帮助都会受到赞赏。错误来自第8行。
代码如下:
<!DOCTYPE html>
<html>
<head>
<title>Form Testing</title>
<meta charset="utf-8"/>
</head>
<body>
<?php
if($_POST['formSubmit'] == "Submit") {
$errorMessage = "";
$varName = htmlspecialchars($_POST['formName'], ENT_QUOTES, 'UTF-8');
$varMovie = htmlspecialchars($_POST['formMovie'], ENT_QUOTES, 'UTF-8');
if(empty($varName)){
$errorMessage .= "<li>You forgot to enter a name!</li>";
}
if(empty($varMovie)){
$errorMessage .= "<li> You forgot to enter a movie!</li>";
}
if(!empty($errorMessage)){
echo("<p> There was an error with your form: </p> \n");
echo("<ul>".$errorMessage. "</ul> \n");
}else{
$fs = fopen("mydata.csv","a");
fwrite($fs,$varName . ", " . $varMovie . "\n");
fclose($fs);
header("Location: ThankYou.html");
echo "Hello ".$varName.". Your favorite movie is: ".$varMovie."!";
exit;
}
}else{
echo "Welcome! Please enter your name and movie preference";
}
?>
<form action="index.php" method="post">
Which is your favorite movie?
<input type="text" name="formMovie" maxlength="50" value="<?=$varMovie;?>">
What is your name?
<input type="text" name="formName" maxlength="50" value="<?php echo $varName;?>">
<input type="submit" name="formSubmit" value="Submit">
</form>
</body>
</html>
答案 0 :(得分:2)
您认为以下是什么?
<!DOCTYPE html> <---output
<html> <---output
<head> <---output
<title>Form Testing</title> <---output
<meta charset="utf-8"/> <---output
</head> <---output
<body> <---output
<?php
...
header(...); // oops... output already performed...
答案 1 :(得分:1)
所有HTML,甚至标题都会引发你的错误。取出标签和所有HTML,然后重试。
答案 2 :(得分:1)
在标题之前没有输出发送意味着它真的!
<!DOCTYPE html>
<html>
<head>
<title>Form Testing</title>
<meta charset="utf-8"/>
</head>
<body>
是在标题之前发送的输出。