php 在同一页面上验证,然后通过不同的 php 进行处理

php validate on same page and then process through different php

我是 PHP 的新手,自己已经学会了一些东西,但我在这方面陷入了困境。我有一个表单可以自我验证并在同一页面上显示错误。填写并验证信息后,我需要通过单独的 PHP 脚本对其进行处理,该脚本会向我发送电子邮件,post 将信息保存到 .csv 文件,并显示确认页面。我目前有这两个东西在工作,但不是在一起。换句话说,我的表单将对自己进行验证,但信息无处可去。这显然是没有用的。另外,我可以通过将操作设置为我的 PHP 脚本来让表单执行所有其他功能,但是字段是否填写并不重要,它会发送任何内容。我已经尝试了从会话、函数到包含的所有内容,但我什至不记得还有什么可以让它发挥作用。我什至尝试将我的错误设置为一个数组,然后对结果调用 TRUE/FALSE 函数以使其验证然后重定向。我在同一页面上得到了验证结果,但无论如何都发送了所有信息,除了显示在空白页面上之外什么都不做。

请不要回复这是重复的。这是我至少一个星期一直在研究和研究的问题。我已经阅读了本网站和其他网站上的许多话题,但没有找到有效的答案。
我不想在客户端验证然后通过 PHP 发送。我还需要验证同一页面并确保保留任何先前输入的响应(我的表单当前所做的),因为有许多字段是必需的。

我正在 post 编写我的部分代码以保留必要的信息。正如我所说,如果我将操作设置为 运行,我的验证和 PHP 脚本都在独立工作。

这是验证的一部分:

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["childsfirstname"])) {
    $childsfirstnameErr = "Child's first name is required.";
  } else {
    $childsfirstname = test_input($_POST["childsfirstname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$childsfirstname)) {
      $childsfirstnameErr = "Only letters and white space allowed";
      die;  
    }
  }

  if (empty($_POST["childslastname"])) {
    $childslastnameErr = "Child's last name is required.";
  } else {
    $childslastname = test_input($_POST["childslastname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$childslastname)) {
      $childslastnameErr = "Only letters and white space allowed";
      die;  
    }
  }

   if (empty($_POST["month"])) {
    $monthErr = "Child's birthday is required.";
  } else {
    $month = test_input($_POST["month"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[0-9]*$/",$month)) {
      $monthErr = "Only numbers allowed";
      die; 
    }
  }
function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

这是表格的一部分:

<div id="Field" style="left: 0px; top: 0px"><strong>Youth's:</strong> 
        First Name: 
            <input type="text" name="childsfirstname" style="width: 220px" value="<?php echo $childsfirstname;?>"/>
            &nbsp;&nbsp;&nbsp; 
        Last Name: 
            <input type="text" name="childslastname" style="width: 300px" value="<?php echo $childslastname;?>"/>
    </div>
    <div id="parent" class="error"> 
        <div id="error1a" style="right: 561px"> <?php echo $childsfirstnameErr;?></div>
        <div id="error1b"> <?php echo $childslastnameErr;?></div> 
    </div>

虽然我知道这里没有代码表明我正在尝试重定向以发送信息,但请相信我已经进行了多次尝试并且我正在寻找的是最好的执行此操作的方式以及有关如何执行此操作的一些实际指导。只要它有效,无论是包含还是需要、会话还是其他,只要它是 PHP 和 验证自我,然后在验证完成且表单无错误后提交给另一个 PHP 脚本。

非常感谢任何和所有的帮助,尤其是因为我是在自愿的基础上这样做的。预先感谢任何可以提供帮助的人。

这是我的 PHP 脚本的开头和结尾 - 我将省略中间部分,因为总共有 16 个基本相同的书面验证。
如果 ($_SERVER["REQUEST_METHOD"] == "POST") {

if (empty($_POST["childsfirstname"])) {
  $Err[1] = "Child's first name is required.";
 }else {
  $childsfirstname = test_input($_POST["childsfirstname"]);
    if (!preg_match("/^[a-zA-Z ]*$/",$childsfirstname)) {
    $Err[1] = "Only letters and white space allowed";
  }
}

  if (empty($_POST["childslastname"])) {
  $Err[2] = "Child's last name is required.";
  } else {
  $childslastname = test_input($_POST["childslastname"]);
    if (!preg_match("/^[a-zA-Z ]*$/",$childslastname)) {
    $Err[2] = "Only letters and white space allowed";
  }
}

。 . .

if (empty($_POST["date"])) {
$Err[15] = "Date required.";
}else {
$date = test_input($_POST["date"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[0-9]*$/",$date)) {
  $Err[15] = "Letters are not allowed"; 
 }
}

if (empty($_POST["checkbox"])) {
$Err[16] = "VALIDATION REQUIRED";
}else {
$checkbox = test_input($_POST["checkbox"]);
 }
}  

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


?>

目前没有任何尝试传递表单信息 - 只有验证有效。我不断地恢复到正在工作的东西,这样我就不会破坏正在工作的东西。

您可以使用两种方法。

第一次使用 header() 将您的脚本重定向到所需的页面。

if(have_valid_data){    
header('Location: email.php');
}

第二种方法是使用 jQuery 验证插件之类的东西来验证您的表单。然后在验证成功后使用表单标签上的 action 属性重定向到您想要的页面。这是 jQuery 插件的 link。

我用它来验证我的所有表格。它非常易于使用,具有很多功能,并且可以自定义以执行您想要的任何操作。

https://jqueryvalidation.org/

附加示例

这只是一个验证表单的示例。您检查所有条件,如果它们产生错误,那么您可以将该错误添加到数组中,比如 $errors。

如果完成后 $errors 数组为空,那么您没有任何错误,您可以假设您的表单已通过验证。然后你做任何你想要的额外代码。在您的情况下,您将使用 header 函数告诉 php 脚本转到另一个页面并在那里执行脚本。

您也可以使用 include/require 并将该页面的脚本包含在当前页面代码中。我会选择那个选项。

如果 $errors 数组中有错误,则显示错误。

//I would use one variable(an array) for your errors.
if (empty($_POST["childsfirstname"])) {

  $errors[] = "Child's first name is required.";

}

if (empty($_POST["month"])) {

  $errors[] = "Child's birthday is required.";

}

if(!isset($errors) && empty($errors)){  //<---This means you have no errors.

    //Since you have no errors you can do what you want to do with the info.
  header('Location: your_email_page.php'); 

  //OR

  //include 'your_email_page.php';  //<-- I prefer this way but sometimes header() has a purpose too.

  exit();  //End the script.

}else {

  echo '<ul><li>' . implode('</li><li>', $errors) . '</li></ul>'; //<--Display your errors.

}

请花时间研究这个示例,然后将其应用到您自己的代码中。

1) 记住isset()函数。有人可以 bypass/edit 你的 html 表格。

2) 切勿使用 die / exit,但仅用于测试目的 - 或在极少数情况下,您别无选择。

3) 要回答您的问题,您的表单应将数据(表单操作属性)提交到同一页面。如果您发现表单已提交,您将在那里进行所有检查,并且您将在表单中显示适当的错误,甚至可能重新填写输入。有人说对安全不好,我说不充值对用户体验不好

如果您发现表单提交正确,则使用

将用户重定向到另一个页面
header('Location: /success-script.php');
exit;

当使用 header() 时,您必须在之后立即使用 exit,因为您正在重定向,所以您真的不想 运行 其余代码。如果您不这样做,一个简单的用户将永远不会知道其中的区别。儿童黑客可以很容易地看到其余代码的结果,有时这是一个真正的威胁。

希望对您有所帮助!

大纲:

IS FORM POSTED?

    YES

        IS FORM VALID?

            YES

                Process data

                HTTP redirect and exit

            NO

                Render form with errors
    NO

        Render blank form

在验证检查结束时,您可以将数据传递给其他函数,然后重定向,例如:

if(
    empty($childsfirstnameErr) &&
    empty($childslastnameErr)  &&
    empty($monthErr)
)
{
    email_the_data($data);
    store_to_csv($data);
    // Redirect and exit here.
}

我在此处添加了一个稍微修改过的代码示例,其中只有两个表单字段:

https://hastebin.com/abekobuyux.xml

这里是一个稍微重构的版本:

https://hastebin.com/agomosikim.xml

后一种风格可以更容易地测试每个组件。

这个模型我为你修改。希望对你有帮助。

<?php // php1.php
  $torf = "false";
  $firstname = "donald";
  $lastname = "trump";
  $firstnameErr = "";
  $lastnameErr = "";
  if (isset($_POST["firstname"])) { // if submitted, validate
    $torf = "true";
    $firstname = $_POST["firstname"];
    $lastname = $_POST["lastname"];
    if ($firstname != "george") {
      $torf = "false"; 
      $firstnameErr = "firstname must be george"; }
    if ($lastname != "washington") {
      $torf = "false"; 
      $lastnameErr = "lastname must be washington"; }
  }    
  echo <<<EOD
<!DOCTYPE html>
<html>
<head>
<script>
  "use strict";
window.onload = function() {
  if (${torf}) { // true if php OKs it
    var elt = document.getElementsByName("myform")[0];
    elt.action = "php2.php"; // go to 2nd php
    elt.submit(); }
}
</script>
</head>
<body>
  <form name="myform" action="" method="post">
  First Name:
  <input type="text" name="firstname" value="${firstname}"/><br />
  Last Name: 
  <input type="text" name="lastname" value="${lastname}"/><br />
  ${firstnameErr}<br />
  ${lastnameErr}<br /> 
  <input type="submit" value="Submit" />
  </form>
</body>
</html>
EOD;
?>

<?php // php2.php
  echo "Am in php2.php; $_POST data is:<br />\n";
  echo json_encode($_POST);
?>

编辑:(而不是你的 "submit",我想问你的 "form" 声明。没什么大不了的。)我觉得整个世界但我错了,我是只有一个权利。我正在寻找任何反驳这一点的东西。以下是 "get it to work".

的说明
// #1 change this:
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
// to this:
  $torf = "false";
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $torf = "true";
// end

// #2 in your php code, every place that you find a validation error, insert this:
  $torf = "false";
// end

// #3 add id="formid" to your <form statement:
  <form id="formid" ..
// end

// #4 change this:
  </head>
// to this:
  <script>
  "use strict";
window.onload = function() (
  if ( <?php echo $torf; ?> ) { // true if php OKs it
    var elt = document.getElementById("formid");
    elt.action = "sendemail_script.php"; // go to email, etc.
    elt.submit(); }
}
  </script>  
  </head>
// end

// guaranteed to work! :)

编辑 2:

// I've numbered the changes #1 to #4.  I assume you've checked them.
// > Where exactly do I put "$torf" ?
// $torf appears in changes #1, #2, and #4. Which one is unclear?

// Look at the page source in your browser
// (In chrome, I right-click and hit "view page source").
// I assume the line after "use strict"; is
  if (false) {
// correct?

//In your form, change
        First Name:
// to
        First Name: X <?php echo $torf; ?> X
// I assume that "X false X" will result, correct?

// For change # 2, your changes are like this, correct? :
// before change
  if (empty($_POST["childsfirstname"])) {
    $childsfirstnameErr = "Child's first name is required.";
// after change
  if (empty($_POST["childsfirstname"])) {
    $torf = "false";
    $childsfirstnameErr = "Child's first name is required.";

// $torf should be "true" if there are no validation errors.
// It must be getting set to "false" somewhere where it shouldn't be.
// Look for that.

// Why is it that you "die"?
// Doesn't that prevent validating the rest of the fields?
// Do you find validation errors one at a time?

// Please check for unintended "false" and I'll think about it.

感谢所有提供帮助的人!一些信息有助于让我找到解决方案。我能够使用来自@dcromley 和@Joseph_J 的信息。我将所有错误设置为一个数组,然后使用@dcromley 建议的 true/false 设置。

     `$Error = "false";
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
      $Error = "true";
      if (empty($_POST["childsfirstname"])) {
    $Error = "false";
      $Err[1] = "Child's first name is required.";    
    }else {
    $childsfirstname = test_input($_POST["childsfirstname"]);
     if (!preg_match("/^[a-zA-Z ]*$/",$childsfirstname)) {
    $Error = "false";
    $Err[1] = "Only letters and white space allowed";
    }
  }

然后我在我的 html 中放置了一个隐藏的文本字段来收集 $Error = "true" 或 $Error = "false" 并设置一个函数来包含我的下一个 php 如果 $Error = "true".

<input name="Err" type="hidden" value="<?php echo $Error ?>" style="width: 945px"/>
    <div id="submit">
<label>&nbsp;<strong><input id="submit" name="Submit" type="submit" value="Submit" style="left: 0px; top: 0px" /></strong>
</label>
    </div>
&nbsp;</div>
</form>

 <?php 
 if(isset($_POST['Submit']) && ($Error === "true")){ 
 enter();
 }
 ?>

由于我无法(出于某种未知原因)让 header 工作,这就是我使用 include 的原因。为了在确认出现后隐藏表格,我在表格之前和表格开头这样做:

    $style = "";
    if($Error === "true"){
     $style = "style='display:none;'";
    }

?>
<div id="wrap">
<form id="RegForm" method="post" action= "<?php echo htmlspecialchars  ($_SERVER["PHP_SELF"]);?>">