user1730332
user1730332

Reputation: 85

How can I redirect users to different pages based on session/form data is valid or not in PHP?

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>



Upvotes: 0

Views: 110

Answers (1)

Parag Tyagi
Parag Tyagi

Reputation: 8960

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.

Upvotes: 4

Related Questions