我在PHP方面还很陌生,并且正在尝试为我的网站建立一个简单的联系我们。我有发送表单,但是由于某种原因,每次我重新加载页面时,它也发送空白消息。我在下面贴了一些表格。
这里有任何帮助/您可以提供的任何提示。
<?php
$name_error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Whoops! Please enter your full name";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Whoops! Only letters and white spaces are allowed in a name";
}
}
if ($name_error == ''){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'myemail@gmail.com';
$subject = 'Contact Us Form Submission';
if (mail($to, $subject, $message_body )){
$success = "Your message has been sent. A representative will be in contact with you shortly.";
$name = $email = $phone = $message = $inquiry = $hear = $success = '';
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
答案 0 :(得分:0)
您的“邮件”逻辑需要放在服务器请求方法中,一个简单的解决方法是将if逻辑复制到邮件逻辑中。即
if($_SERVER["REQUEST_METHOD"] == "POST"){
if (mail($to, $subject, $message_body )){
$success = "Your message has been sent. A representative will be in contact with you shortly.";
$name = $email = $phone = $message = $inquiry = $hear = $success = '';
}
}
当然,您也可以删除当前的if语句并放在方括号中,然后将其放在代码末尾(因为不需要那么早就破坏if语句)
即
<?php
$name_error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Whoops! Please enter your full name";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Whoops! Only letters and white spaces are allowed in a name";
}
}
if ($name_error == ''){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'myemail@gmail.com';
$subject = 'Contact Us Form Submission';
if (mail($to, $subject, $message_body )){
$success = "Your message has been sent. A representative will be in contact with you shortly.";
$name = $email = $phone = $message = $inquiry = $hear = $success = '';
}
}
// <--- ADD CLOSING BRACKET HERE
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}