【发布时间】:2015-12-18 05:52:40
【问题描述】:
我是 PHP 新手,目前正在重新使用 HTML。我已经制作了一个表格,并通过 PHP 发送和验证了数据,但我只是在数据经过验证并且正确后才尝试将电子邮件发送给自己。目前,如果页面已加载,我认为它会发送一封电子邮件,并且只要我点击提交而数据不正确,它就会发送。
这里是我验证数据的地方:
<?php
//Set main variables for the data.
$fname = $lname = $email = $subject = $website = $likedsite = $findoption = $comments = "";
//Set the empty error variables.
$fnameErr = $lnameErr = $emailErr = $subjectErr = $commentsErr = $websiteErr = $findoptionErr = "";
//Check to see if the form was submitted.
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check the 'First Name' field.
if (empty($_POST["fname"]))
{
$fnameErr = "First Name is Required.";
}
else
{
$fname = validate_info($_POST["fname"]);
}
//Check the 'Last Name' field.
if (empty($_POST["lname"]))
{
$lnameErr = "Last Name is Required.";
}
else
{
$lname = validate_info($_POST["lname"]);
}
//Check the 'E-Mail' field.
if (empty($_POST["email"]))
{
$emailErr = "E-Mail is Required.";
}
else
{
$email = validate_info($_POST["email"]);
//Check if valid email.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid E-Mail Format.";
}
}
//Check the 'Subject' field.
if (empty($_POST["subject"]))
{
$subjectErr = "Subject is Required.";
}
else
{
$subject = validate_info($_POST["subject"]);
}
//Check the 'Website' field.
if (empty($_POST["siteurl"]))
{
$website = "";
}
else
{
$website = validate_info($_POST["siteurl"]);
//Check if valid URL.
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL.";
}
}
//Check the 'How Did You Find Us' options.
if (empty($_POST["howfind"]))
{
$findoptionErr = "Please Pick One.";
}
else
{
$findoption = validate_info($_POST["howfind"]);
}
//Check the comment box.
if (empty($_POST["questioncomments"]))
{
$commentsErr = "Questions/Comments are Required.";
}
else
{
$comments = validate_info($_POST["questioncomments"]);
}
//Pass any un-required data.
$likedsite = validate_info($_POST["likedsite"]);
}
function validate_info($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
抱歉有点冗长。
这是我尝试发送电子邮件的地方。我尝试了两种不同的尝试,结果都一样。
<?php
if (!empty($fnameErr) || !empty($lnameErr) || !empty($subjectErr) || !empty($emailErr) || !empty($commentErr) || !empty($websiteErr) || !empty($findoptionErr))
{
echo "Sent!!";
}else
{
echo"Not Sent!!";
}
//Make the message.
$message =
"
First Name: $fname.\n
Last Name: $lname.\n
Website: $website\n
Did They Like the Site? $likedsite.\n
How They Found Us. $findoption.\n
Question/Comments:\n
$comments.
";
$message = wordwrap($message, 70);
$headers = "From: $email";
mail("me@gmail.com", $subject, $message, $headers);
?>
再次对篇幅感到抱歉。提前感谢也很抱歉,如果这是一个双重问题或描述不够,我也是堆栈溢出的新手。
【问题讨论】:
-
替换||通过 && 所以它会算作 'and' instear of 'or'
-
我只是试了一下,结果显示“未发送”。当我完整且正确地填写表格且没有错误时,它并没有更改为“已发送”。
-
我的错,我以为你使用的是输入而不是错误变量啊,尝试替换 ||通过 && 并删除!在 each 前面,所以如果它们都是空的(没有错误)它应该发送。
-
谢谢。我现在试试。也有点我的错。我完全应该注意到这一点。
-
@TheGamingMann,我用一些代码解决方案发布答案。一旦每个验证消息变量都为空,则只有网站发送邮件。