我的联系表单每次访问页面时都会发送黑色电子邮件,只要有人填写表单并点击发送,就会发送另一封电子邮件。我正在努力学习如何验证我的联系表格的数据,并且整天运气不佳。我知道很少有php或javascript代码,但是我已经从之前编写的代码中做到了最好。
有什么想法吗?
<form action="" method="post" style="width:100%;">
Name*<br> <input type="text" name="name" style="width:50%;" ><br/><br/>
Email*<br> <input type="text" name="email" style="width:50%;"> <br/><br/>
Phone*<br> <input type="text" name="phone" style="width:50%"> <br/><br/>
<input name="submitted" type="submit" value="Send" >
<input name="" type="reset" value"Reset">
</form>
<?php
if (isset($_REQUEST['submitted'])) {
// Initialize error array.
$errors = array();
// Check for a name
if (!empty($_REQUEST['name'])) {
$name = $_REQUEST['name'];
$pattern = "/^[a-zA-Z0-9\_]{2,20}/";]
if (preg_match($pattern,$name)) {
$name = $_REQUEST['name'];
} else {
$errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';
}
} else {
$errors[] = 'You forgot to enter your name.';
}
//Check for a valid phone number
if (!empty($_REQUEST['phone'])) {
$phone = $_REQUEST['phone'];
$pattern = "/^[0-9\_]{7,20}/";
if (preg_match($pattern,$phone)) {
$phone = $_REQUEST['phone'];
} else {
$errors[] = 'Your phone number can only be numbers.';
}
} else {
$errors[] = 'You forgot to enter your phone number.';
}
//Check for a valid email
if (!filter_var($_REQUEST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'The email provided is not valid.';
}
} else {
$email = $_REQUEST['email'];
}
//End of validation
if (empty($errors)) {
$from = "From: " . $_REQUEST['email'];
$to = "myemail@myemail.com";
$subject = "A comment from " . $name . "";
$message = "Message from " . $name . "
Phone: " . $phone . "
Email: " . $_REQUEST['email'] . "";
mail($to,$subject,$message, $from);
}
//Print Errors
if (isset($_REQUEST['submitted'])) {
// Print any error messages.
if (!empty($errors)) {
echo '<hr /><h3 >The following occurred:</h3><ul>';
// Print each error.
foreach ($errors as $msg) {
echo '<li>'. $msg . '</li>';
}
echo '</ul><h3 >Your mail could not be sent due to input errors.</h3><hr />';
} else {
echo '<hr /><h3 align="center" >Your mail was sent. Thank you!</h3><hr /><p>Below is the message that you sent.</p>';
echo "Message from " . $name . "<br />Phone: ".$phone."<br />Email:" . $email;
}
}
//End of errors array
?>
答案 0 :(得分:1)
您在if (isset($_POST['submitted']))
区块之外发送邮件。我认为问题是你在这里有一个额外的支撑:
//Check for a valid email
if (!filter_var($_REQUEST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'The email provided is not valid.';
} // <<===== HERE
} else {
$email = $_REQUEST['email'];
}
因此,else
子句未与电子邮件验证相关联,它已连接到if (isset($_POST['submitted']))
。因此,当表单尚未提交时,您需要设置$email
,然后进入发送电子邮件的代码。
答案 1 :(得分:0)
尚未声明的数组仍为空。
变化
if (empty($errors)) {
到
if (isset($errors) && empty($errors)) {