我有 function confirm()
,当他成功提交联系表格时,他应该向用户发送弹出确认。它似乎工作正常,但是如果用户按浏览器中的页面刷新再次触发函数,如果我从链接页面导航回页面,则再次触发confirm()
函数。
我不明白为什么,因为在 confirm()
函数之前我重置两个变量,这些变量应阻止被调用的函数。
<?PHP
/* Set e-mail recipient */
$myemail = "bob@arnold.com";
/* Introduce the email message */
$themessage = "";
$nameErr = $emailErr = $subjectErr = $commentErr = "";
$name = $email = $subject = $comment = "";
$nosubmit = 0; //variable to check whether form data valid
$nosubmit_two = 0; //variable to check whether form data valid
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function confirm() {
echo "<script>";
echo "window.confirm('Thank you for your message. You should get an
email confirmation. I will reply to you in full as soon as I can. Have
a nice day!')";
echo "</script>";
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["Name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "* Only letters and white space allowed";
}
else $nosubmit = 1;
$email = test_input($_POST["Email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "* Invalid email format";
}
else $nosubmit_two = 1;
$subject = test_input($_POST["Subject"]);
$comment = test_input($_POST["Comment"]);
if ($nosubmit == "1" && $nosubmit_two == "1") {
$themessage = "Message From:".$name."on the matter
of:".$subject."Message reads:".$comment;
mail($myemail, $subject, $themessage);
$name = $email = $subject = $comment = "";
$nosubmit = 0;
$nosubmit_two = 0;
confirm(); // write function to alert user that email has been sent;
}
} // closes main if statement
?>
您重置的变量仅用于该请求。提供页面时,PHP会自动清除它们。当用户按"刷新"按钮时,浏览器将发送另一个发布请求,其信息与上次发送数据完全相同。它执行与以前完全相同的请求。
为了解决此问题,您可以使用PHP header
将用户重定向到某个页面,也可以存储已发送邮件已发送的某个地方(例如,在文件,数据库等中)。最简单的方法是用户$_SESSION
您首先必须在生成任何输出之前,在代码顶部的某个地方启动session_start()
。比您设置的$_SESSION['mailHasSent'] = true
发送邮件时,您在发送另一封邮件之前验证该会话变量是否设置。
您在$ _Session中存储的变量保留在多个页面刷新上。更多信息在这里