PHP验证问题解决方法

3
我之前有一些Python编程经验,但被要求为某人构建一个网页,所以我尝试使用Bootstrap框架、HTML和PHP(边学边做)构建了一个基本页面。
除了订阅表单没有验证以外,一切都完美无缺。因此,我认为最好实现一些验证,但是该表单似乎没有反应,并且即使表单完全为空,脚本仍然会完成并发送电子邮件。
这是否是因为表单在“模态”中?我对此仍然很生疏,如果这已经涉及到了,我向您道歉,但我找不到能帮助我的答案。
我附上了模态表单的HTML和PHP代码。
<!-- Modal form -->
<div class="modal fade" id="Subscribe" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Subscribe for updates!</h4>
      </div>
      <div class="modal-body">
            <div class="container-fluid">
              <form method="post" action="Submit.php">
                <div class="row">
                    <div class="col-xs-12">
                        <div class="input-group" style="margin-bottom: 5px;">
                            <span class="input-group-addon" id="first">First Name</span>
                            <input type="text" class="form-control" placeholder="John" name="first" aria-describedby="First-Name">
                            <span class="input-group-addon error" style="color: red">* <?php echo $firstErr;?></span>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-12">
                        <div class="input-group" style="margin-bottom: 5px;">
                            <span class="input-group-addon" id="last">Surname</span>
                            <input type="text" class="form-control" placeholder="Smith" name="surname" aria-describedby="Surname">
                            <span class="input-group-addon error" style="color: red">* <?php echo $lastErr;?></span>
                        </div>
                    </div>
                 </div>
                 <div class="row">
                    <div class="col-xs-12">
                        <div class="input-group" style="margin-bottom: 5px;">
                            <span class="input-group-addon" id="email">Email</span>
                            <input type="email" class="form-control" placeholder="something@example.co.uk" name="email" aria-describedby="Email">
                            <span class="input-group-addon error" style="color: red">* <?php echo $fromErr;?></span>
                        </div>
                     </div>
                </div>
                <div class="row">
                    <div class="col-xs-12">
                        <div class="input-group" style="margin-bottom: 5px;">
                            <span class="input-group-addon" id="notes">Notes</span>
                            <textarea class="form-control" rows="3" placeholder="Please put anything else you want to say here" name="notes" aria-describedby="Notes">
            </textarea>
                        </div>
                     </div>
                </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="submit" name="submit" value="submit" class="btn btn-primary">Send</button>
              </div>
            </form>
          </div>
      </div>
    </div>
  </div>
</div>

文件名为'Submit.php'

<?php 

// define variables and set to empty values
$fromErr = $firstErr = $lastErr = $notesErr = "";
$from = $first_name = $last_name = $notes = "";

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

if (isset($_POST['submit'])) {
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
  }
  if (empty($_POST["first"])) {
    $firstErr = "Name is required";
  } else {
    $first_name = test_input($_POST["first"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$first_name)) {
      $firstErr = "Only letters and white space allowed"; 
    }
  }
  if (empty($_POST["surname"])) {
    $lastErr = "Surname is required";
  } else {
    $last_name = test_input($_POST["surname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$last_name)) {
      $lastErr = "Only letters and white space allowed"; 
    }
  }
    $notes = test_input($_POST["notes"]); // this is the senders message

    $to = "myemail@domain.com";  // this is your Email address
    $subject = "Website subscription from " . $first_name . " " . $last_name; //Subject line

    $message = "First name: " . $first_name . "<br>" . "Surname: " . $last_name . "<br>" . "Email: " . $from . "<br>" . "Notes: " . $notes;

    $headers = "From: " . $from . "\r\n";
//  $headers .= "CC: myemail@domain.comr\n"; option to CC
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    mail($to,$subject,$message,$headers);
    header('Location: ./index.html#Thanks'); // redirect back to main page with 'Thanks' Modal open
}
?>

我非常希望能得到任何帮助!

编辑:

以防有人想知道我最终是如何到达需要的位置的:@leepowers的答案是朝着正确方向迈出的巨大一步,这让我能够检查是否有任何错误并在有错误时阻止发送电子邮件,然后我学习了“会话”,我以非常混乱的方式将错误存储在会话中,以便在返回表单时重用它们。

// Gather all errors into an array
$errors = array($fromErr, $firstErr, $lastErr);
// Remove any empty error messages from the array
$errors = array_filter($errors);
// An array with more than zero elements evaluates `true` in a boolean context
if ($errors) {
    $_SESSION["fromErr"] = $fromErr;
    $_SESSION["firstErr"] = $firstErr;
    $_SESSION["lastErr"] = $lastErr;
    die(header('Location: ./index.html#Subscribe'));
} else { // send email

在我的html页面中,我有一些JS来将“重定向”指向一个模态框:

<script>
$(document).ready(function() {

  if(window.location.href.indexOf('#Thanks') != -1) {
    $('#Thanks').modal('show');
 } else if(window.location.href.indexOf('#Subscribe') != -1) {
    $('#Subscribe').modal('show');
  }
});
</script>

现在,我的表单中每个输入都有一个专门用于错误的字段:
<div class="input-group" style="margin-bottom: 5px;">
                        <span class="input-group-addon" id="email">Email</span>
                        <input type="email" class="form-control" placeholder="something@example.co.uk" name="email" aria-describedby="Email">
                        <span class="input-group-addon error" style="color: red">* <?php echo $_SESSION["fromErr"];?></span>

谢谢大家的帮助。这段话与IT技术无关。

2
你没有对$lastErr或者$firstErr做任何处理,所以邮件会直接发送。尝试在mail($to,$subject,$message,$headers);之前添加一个条件,要求这两个变量都为空。 - chris85
我不确定其他人是否也这样做,但我通常将所有错误附加到一个数组中,然后在检查多个条件时检查是否发生任何错误,只需执行 if (count($errors) > 0) { handleError(); } else { doSomething(); } - Mike
另外,test_input() 函数具体是做什么的? - Mike
@Mike 函数被定义在顶部。 - andrew
1
@andrew 哦,你说得对。我不知道怎么错过了这个。@OP:除非你正在运行 PHP < 5.4 并将 magic_quotes_gpc 设置为 true,否则你应该删除 stripslashes() - Mike
2个回答

1
代码需要检查是否存在错误消息,并在发送电子邮件之前停止执行。可以像以下代码一样,在验证检查之后插入此代码:
// Gather all errors into an array
$errors = array($emailErr, $firstErr, $lastErr);
// Remove any empty error messages from the array
$errors = array_filter($errors);
// An array with more than zero elements evaluates `true` in a boolean context
if ($errors) {
  // Output error messages and exit the script.
  die(implode("<br>\n", $errors));
}

这是一个非常基本的例子。最好在脚本顶部初始化$errors数组,然后在出现错误时向该数组添加错误消息。

当然,现在看起来很明显!我的代码只是创建错误,然后无论如何都会发送电子邮件...我会看看是否有足够的时间在午餐时间修改我的代码并进行测试,谢谢。 - Andy
太棒了!将错误输出到页面上,这是一个很好的开始。难道没有办法将其发送回原始表单的“error”<span>中吗? - Andy

1

尝试这个,我没有验证数据,你需要自己验证。另外,你发布的代码中$from是空的。

   <?php
//if "email" variable is filled out, send email
  if (isset($_REQUEST['email']))  {

  //Email information
  $to = "Your_email_id";
  $email = $_REQUEST['email'];
  $first_name=$_REQUEST['first'];
  $last_name=$_REQUEST['surname'];
  $name=$first_name.' '.$last_name;
  $subject ="Your subject";
  $message = $_REQUEST['notes'];

  //send email
  mail($to, $subject, $message, "From:" . $email." Name:".$name);

  //Email response
  echo "Thank you for contacting us!";
  }

  //if "email" variable is not filled out, display the form
  else  {


  }
?>

为什么应该让 OP 尝试这个?你去掉了验证。 - chris85
谢谢您的回复,但我并没有遇到发送电子邮件的问题,验证是我无法完全正确处理的部分。不过,您指出了$from的错误,$email也应该是$from,而不是$emailErr,所以非常感谢您。 - Andy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接