所以我在我的网站example.com/pp.php中有表单,该表单的操作是pp.php,因为该脚本不是某些外部文件,而是在该页面内部。问题是我需要输入标题(“Location:http://example.com/pp.php#contactForm”);因为按下发送按钮后我想重新加载页面的确切位置是/pp.php#contactForm。但标题位置不起作用...我是PHP的新手,所以对于愚蠢的问题感到抱歉。
<form action="pp.php" method="post">
<label>Name:</label>
<input type="text" name="name" value="<?php if($_POST['name']) {
echo $_POST['name']; } ?>" />
<label>Email:</label>
<input type="text" name="email" value="<?php if($_POST['email'])
{ echo $_POST['email']; } ?>" />
<label>Message:</label><br />
<textarea name="message" rows="20" cols="20"><?php
if($_POST['message']) { echo $_POST['message']; } ?></textarea>
<label><img src="captcha.php"></label>
<input type="text" name="code"> <br />
<input type="submit" class="submit" name="submit" value="Send
message" />
</form>
这是php
<?php
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*
(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "You didn't type in a message. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try
again. <br />";
}
if (empty($error)) {
$from = 'From: ' . $name . ' <' . $email . '>';
$to = "mail@gmail.com";
$subject = "New contact form message";
$content = $name . " has sent you a message: \n" . $message;
$success = "<h3>Thank you! Your message has been sent!</h3>";
mail($to,$subject,$content,$from);
}
}
?>
<?php
if (!empty($error)) {
echo '<p class="error"><strong>Your message was NOT sent<br/> The
following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
header("Location: http://example.com/pp.php#contactForm");
?>
答案 0 :(得分:2)
输出到DOM后,您无法使用 header()
进行重定向:
请记住,在发送任何实际输出之前,必须通过普通HTML标记,文件中的空行或PHP来调用header()。
因此,您需要删除行中的 echo
语句:
if (!empty($error)) {
echo '<p class="error"><strong>Your message was NOT sent<br/> The
following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
致电之前:
header("Location: http://example.com/pp.php#contactForm");
答案 1 :(得分:0)
试试这个:
header('Location: pp.php#contactForm');
并确保在此行之前无论如何都不输出任何html标记。
比如echo $success;