vincent
vincent

Reputation: 1390

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

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:

<!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?

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

Upvotes: 12

Views: 90293

Answers (4)

Francisco Aguilera
Francisco Aguilera

Reputation: 3482

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.

Upvotes: 0

Drixson Ose&#241;a
Drixson Ose&#241;a

Reputation: 3641

When all your conditions are met you can use 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.

Upvotes: 7

Lazik
Lazik

Reputation: 2520

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

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

<!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>");
}
?>

Upvotes: 6

invisal
invisal

Reputation: 11171

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:

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

Upvotes: 0

Related Questions