PHP Redirect to new page after form submission

2020-04-19 05:55发布

问题:

I have a form, which redirects the user to "page1.php" after the form is submitted. What I want to do is to redirect the user to "page2.php" after the form is submitted, but I need to make sure that the POST request was sent. Example:

<form action="page1.php" method="POST">
<input type="text" name="username" />
<input type="text" name="age" />
<input type="submit" value="" />
</form>

When the user clicks on Submit, it redirects him to page1.php. I want to redirect him to page2.php, but I need to make sure that the data is sent to the server. I can't use AJAX. Is there any way to do it with cURL or something like that? Any examples?

Thanks!

回答1:

I guess this works !! In page1.php

<?php
//do establish session
//and check for the input fields obtained via $_POST
if(isset($_POST['name_of_your_field']) && !empty($_POST['name_of_your_field'])){
    if(!mail($to,$subject,$message)){
        header('location:form.php?msg=error');  
    }else{
        header('location:page2.php?msg=succes');
        }
}   
?>


回答2:

You can check if the POST request was sent with something like:

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    // do something...
}

You can create a hidden input in your form and send additional info about the form that is submitted, e.g. action.

Inside you will do your magic and redirect user with:

header('Location: page2.php');
exit();


回答3:

In your 'page1.php' processor, add a 'header' redirect to 'page2.php'.

header("Location: page2.php");
exit;


回答4:

you could do a check if query is complete

example

<?php
$query=mysqli_query(".......your query statement")or trigger_error(mysqli_error());
if($query){
           header("Location:page2.php");
          }
else{
     die('error');
    }
?>


回答5:

In your situation, you can just simple check for the posted data. Like

$username = $_POST['username'];
$age = $_POST['age'];
if($username&&$age){ /* This is to check if the variables are not empty  */
 // redirect to page2
}

It is logical that if those are not empty, meaning they are posted. Even if they are empty, as long as you get there, that means it was posted. There is no need to check if posted or not, what needs to be checked was, if posted data was there.

I hope I made it clear. ^_^ but making sure is not bad at all. Happy coding friend.