简体   繁体   中英

How to $_Post data from submit form PHP after validation

I just saw this codes from this website and thinking to implement it to my project however I cannot get my data on the next page. I am using the test.php as a index and submit.php as a page that will catch the post

here is the codes

test.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") {
   $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: submit.php');
   exit();
  }
}

// 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>

submit.php

<?php
$test=$_POST['lastName'];
echo $test;

?>

Your form action should be the file where you want to get the form submitted values .

change this <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post"> to <form action="submit.php" method="post">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM