简体   繁体   中英

PHP Redirect to new page after form submission

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!

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

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, eg action.

Inside you will do your magic and redirect user with:

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

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

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

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

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.

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