<?php
$name_error = $email_error = $phone_error = $url_error = $last_name_error= "";
$firstName = $lastName = $email = $phone = $message = $url = $success = "";
if (isset($_POST["sendMessage"])) {
if (empty($_POST["firstName"])) {
$name_error = "Name is required";
} else {
$firstName = test_input($_POST["firstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["lastName"])) {
$last_name_error = "Name is required";
} else {
$lastName = test_input($_POST["lastName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastName)) {
$last_name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone_error = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
$phone_error = "Invalid phone number";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $last_name_error == '' and $email_error == '' and $phone_error == '' ){
$message_body = '';
unset($_POST['sendMessage']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'some@gmail.com';
$subject = 'webmaster@example.com';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstName = $lastName = $email = $phone = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
我尝试验证此联系表单。但它不起作用。每当我发送一个电子邮件表单的实时服务器时,只发送消息但名称,电话,电子邮件不发送。请有人帮助我。我从最后一天开始研究它,但没有工作。
答案 0 :(得分:1)
那是因为你根本不发送它们。看看你的代码:
if (mail($to, $subject, $message)){
Yoou正在发送变量$ message作为消息,那很好..但是,让我们来看看这个变量里面是什么:
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
您正在为其分配$_POST["message"]
的值 - 没有别的。
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
我认为你会发送$ message_body而不是$ message,那么它应该可以正常工作:)
希望有所帮助。