函数confirm()只有在有效表单提交后才会在页面刷新后触发

时间:2017-09-02 11:26:58

标签: php forms

我有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

?>

1 个答案:

答案 0 :(得分:0)

您重置的变量仅针对该请求重置。当页面被提供时,PHP会自动清除它们。 当用户按下刷新按钮时,浏览器发送另一个POST请求,其中包含与上次发送数据完全相同的信息。它执行与以前完全相同的请求。

要解决此问题,您可以使用php header将用户重定向到某个页面,或者您可以存储已发送邮件的某个位置(例如,在文件,数据库等中)。用户$_SESSION

最简单的方法

在生成任何输出之前,首先必须在代码顶部的某个位置启动会话session_start()。比你设定的例如发送邮件时$_SESSION['mailHasSent'] = true,并在发送其他邮件之前验证是否设置了此会话变量。

您在$ _SESSION中存储的变量仍会在多个页面刷新时保留。更多信息here