0

I am working with a very simple form and trying to learn php. I have sessions working and post data working but I am trying to redirect the user to next page if the data is valid. I am running some validation which also I am successful with so far but only thing I am not finding is how to go to the next page if the data that they entered in the form is valid.If not it is already printing an error. I am very new to this so any help would be appreciated.

$nameErr = "";
        if($_SERVER["REQUEST_METHOD"] == "POST"){
            if(empty($_POST["fname"])){
                $nameErr = "name is required";
            }
        }

This is how my form looks like. I know I have to change something in the "action" part of the form as of right now it is printing to the same but not sure what. Can I write a if statement or something?

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

  <label for="fname">FirstName:</label>
  <input type="text" class="form-control" name="fname" id="fname" placeholder="Enter First Name">
     <span class="error">* <?php echo $nameErr;?></span>



user1730332
  • 85
  • 1
  • 1
  • 6
  • 2
    A few notes: Do not use `PHP_SELF` as this is unsafe, at least clean the variable before echoing it. Also, while @Parag Tyagi does have the correct answer, and it is a good idea when using PHP `header` but you need to have no output before the `header` and you really should add a `die();` statement afterward the header to ensure the rest of the script does not fire, in this instance. – Martin Feb 12 '15 at 16:35
  • Make sense. It was giving me an error. I will keep that in mind. – user1730332 Feb 12 '15 at 16:41

1 Answers1

4

You can use PHP header

header("Location: /example/par1/");
exit();


In your case:

$nameErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    if(empty($_POST["fname"]))
    {
        $nameErr = "name is required";
    }
    else
    {
        // If validation success, then redirect
        header("Location: http://www.google.com/");
        exit();
    }
}


Note:

Yes, as @Andrei P said in the comments there shouldn't be anything before the header() is called. To be more precise, header functions should be called just after PHP opening tag <?php. For example,

<?php
header('Location: http://www.example.com/');
exit;

Below will give you an error

<html>
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>

For more info can read this.

Community
  • 1
  • 1
Parag Tyagi
  • 8,780
  • 3
  • 42
  • 47