HTML 表单 PHP 发布到 self 以验证或提交到新页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18820013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:16:30  来源:igfitidea点击:

HTML form PHP post to self to validate or submit to new page

phphtmlforms

提问by vincent

Upfront apology. Today is my first day working with php and I finally figured out how to get my page to post back to itself (I'd had the page as .html, instead of .php), but now I'm having trouble figuring out how to take the data to a new page after the form has been validated. I've been working on it for quite a while and I'm fried. Here's a simple example:

提前道歉。今天是我使用 php 的第一天,我终于想出了如何让我的页面发回自身(我将页面作为 .html,而不是 .php),但现在我无法弄清楚如何在表单验证后将数据带到新页面。我已经研究了很长一段时间,我被炸了。这是一个简单的例子:

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// Initialize variables and set to empty strings
$firstName=$lastName="";
$firstNameErr=$lastNameErr="";

// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
   if (empty($_POST["firstName"])) {
      $firstNameErr = "First name is required";
   }
   else {
      $firstName = test_input($_POST["firstName"]);
   }
   if (empty($_POST["lastName"])) {
      $lastNameErr = "Last name is required";
   }
   else {
      $lastName = test_input($_POST["lastName"]);
   }
}

// Sanitize data
function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>

<h2>Find Customer</h2>
<p><span class="error">* required</span></p>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
First Name: <input type="text" name="firstName" value="<?php echo $firstName; ?>"><span class="error">* <?php echo $firstNameErr; ?></span><br><br>
Last Name: <input type="text" name="lastName" value="<?php echo $lastName; ?>"><span class="error">* <?php echo $lastNameErr; ?><br><br>
<input type="submit">
</form>

</body>
</html>

OK. So above, you'll see that the form posts back to itself so it can validate. Good. Now, considering all things are valid, how do I post to another script (action="otherAction.php", maybe?) so the data can actually be processed?

好的。所以在上面,您会看到表单回传给它自己,以便它可以验证。好的。现在,考虑到所有事情都是有效的,我如何发布到另一个脚本(action="otherAction.php",也许?)以便实际处理数据?

Also, any security suggestions are appreciated. I did my best to take security into account. Thanks.

此外,任何安全建议表示赞赏。我尽力考虑到安全性。谢谢。

采纳答案by Drixson Ose?a

When all your conditions are met you can use header('Location: http:mywebsite.com/otherAction.php')

当你的所有条件都满足时,你可以使用 header('Location: http:mywebsite.com/otherAction.php')

// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
   $valid = true; //Your indicator for your condition, actually it depends on what you need. I am just used to this method.

   if (empty($_POST["firstName"])) {
      $firstNameErr = "First name is required";
      $valid = false; //false
   }
   else {
      $firstName = test_input($_POST["firstName"]);
   }
   if (empty($_POST["lastName"])) {
      $lastNameErr = "Last name is required";
      $valid = false;
   }
   else {
      $lastName = test_input($_POST["lastName"]);
   }

  //if valid then redirect
  if($valid){
   header('Location: http://mywebsite.com/otherAction.php');
   exit();
  }
}

In some of my works, my setup is like this but I learned something not good here. That's when you refresh the page after submitting the form , POST values still remains and possible for duplicating entries. Which is not good IMO.

在我的一些作品中,我的设置是这样的,但我在这里学到了一些不好的东西。那是当您在提交表单后刷新页面时,POST 值仍然保留并且可能用于重复条目。这不是好的 IMO。

回答by Lazik

Use javascript to validate, then send the post form to itself or to another page where it can do stuff with the data.

使用 javascript 进行验证,然后将帖子表单发送到它自己或另一个页面,在那里它可以对数据进行处理。

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}
</script>
</head>

<body>
<form name="myForm" action="demo_form.php" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>

</html>

source : http://www.w3schools.com/js/js_form_validation.asp

来源:http: //www.w3schools.com/js/js_form_validation.asp

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// Initialize variables and set to empty strings
$firstName=$lastName="";
$firstNameErr=$lastNameErr="";

// Control variables
$app_state = "empty";  //empty, processed, logged in
$valid = 0;

// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
   if (empty($_POST["firstName"])) {
      $firstNameErr = "First name is required";
   }
   else {
      $firstName = test_input($_POST["firstName"]);
      $valid++;
   }
   if (empty($_POST["lastName"])) {
      $lastNameErr = "Last name is required";
   }
   else {
      $lastName = test_input($_POST["lastName"]);
      $valid++;
   }

   if ($valid >= 2) {
      $app_state = "processed";
   }
}

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

if ($app_state == "empty") {
?>
<h2>Find Customer</h2>
<p><span class="error">* required</span></p>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
First Name: <input type="text" name="firstName" value="<?php echo $firstName; ?>"><span class="error">* <?php echo $firstNameErr; ?></span><br><br>
Last Name: <input type="text" name="lastName" value="<?php echo $lastName; ?>"><span class="error">* <?php echo $lastNameErr; ?><br><br>
<input type="submit">
</form>

</body>
</html>
<?php
}
elseif ($app_state == "processed") {
    if ($firstName == "Vincent") {
        $app_state = "Logged in";
    }
}

if ($app_state == "Logged in") {
    echo("Logged in<br> Hello Vincent</body></html>");
}
?>

回答by invisal

You can check if there is any invalid data, if there is no invalid data, process, then redirect. For example

您可以检查是否有任何无效数据,如果没有无效数据,则处理,然后重定向。例如

 if (empty($firstNameErr) && empty($lastNameErr)) {
       // process the data

       // redirect to other page.
       header('LOCATION: index.php');
       exit();
 }

Noted that you need to do those code before you output any HTML, or else you cannot do the redirection. For example:

请注意,您需要在输出任何 HTML 之前执行这些代码,否则无法进行重定向。例如:

<?php
      // validate the data
      // no error, proccess, then, redirect
?>
html code here.

回答by Francisco Aguilera

Relying on redirection like that is bad for SEO if you are about that stuff. It would be better for SEO for your form to post to another page naturally.

如果你是关于那些东西的,那么依赖像这样的重定向对 SEO 不利。对于 SEO 来说,您的表单自然地发布到另一个页面会更好。