我一直在使用 php 页面向电子邮件地址发送邮件,并一直在尝试添加验证。我在某个地方出错了,但我不确定在哪里?该代码应该在按下提交按钮后开始验证。它应该检查一个字段是否为空,然后针对一组正则表达式进行验证,但是我认为我犯了一个错误。如果表单成功验证,它将发送到我的电子邮件。
<?php
if(isset($_POST{'submit'} )){
$f_name=$_POST['first_name'];
$l_name=$_POST['last_name'];
$email=$_POST['email'];
$message=$_POST['message'];
$to = "email@somewhere.com";
$subject = "A message has been sent from your site";
$comment = "You have been emailed by: $email \n
Message Contents: $message \n
Message sent by $f_name $l_name \n
Email to respond to: $email" ;
if (empty($_POST["f_name"]))
echo "Please enter your first name";
}
else{
if (!preg_match("/^[a-zA-Z ]*$/",$f_name))
{
echo "Your first name does not appear to be valid";
}
}
if (empty($_POST["l_name"]))
echo "Please enter your last name";
}
else{
if (!preg_match("/^[a-zA-Z ]*$/",$f_name))
{
echo "Your last name does not appear to be valid.";
}
}
if (empty($_POST["email"]))
echo "Please enter your email";
}
else{
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
echo "Your email does not appear to be valid.";
}
}
if (empty($_POST["message"]))
echo "Please enter a message";
}
else{
mail($to, $subject, $message);
/* Print a message for the user */
echo "<b>Your message has been sent successfully, details are as followed:</b><br />";
echo "<br /><b>First name: </b>".$f_name;
echo "<br /><b>Last name: </b>".$l_name;
echo "<br /><b>Email: </b>".$email;
echo "<br /><b>Comments: </b>".$message;
echo "<br /><br /><b>Thank you for your comment.</b>";
}else{
?>
<form action="contact_page.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
First Name:<br>
<input name="first_name" type="text" value="" size="30"/><br>
Surname:<br>
<input name="last_name" type="text" value="" size="30"/><br>
Your email:<br>
<input name="email" type="text" value="" size="30"/><br>
Your message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input type="submit" value="Send email" name="submit"/>
<input type="reset" value="Reset Form">
</form>
<?php
?>