In PHP development, it is common to submit data through a form and then redirect to another page for processing. Mastering POST parameter transfer and page redirection is essential for handling user input and implementing interactive features. The following examples illustrate this process in detail.
First, we need to create a form page where users can input information and submit it to the server. Assume the file name is form.php, with the following code:
<!DOCTYPE html> <html> <head> <title>Form Submission Page</title> </head> <body> <h2>Please fill in the information below:</h2> <form method="post" action="process.php"> <label>Name:</label><br> <input type="text" name="name"><br><br> <label>Age:</label><br> <input type="text" name="age"><br><br> <input type="submit" value="Submit"> </form> </body> </html>
This code creates a form with input fields for name and age, using the POST method to submit data to the process.php page.
Next, create the process.php file to handle submitted POST parameters and redirect to the results page:
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST['name']; $age = $_POST['age']; // You can process the received parameters here, such as storing them in a database // Redirect to the result page and pass the parameters header("Location: result.php?name=$name&age=$age"); exit(); } else { echo "Invalid request"; } ?>
Here, we use $_POST to get the submitted name and age, then use the header function to redirect to result.php while passing the data as GET parameters.
Finally, create the result.php page to display the submitted data:
<!DOCTYPE html> <html> <head> <title>Result Page</title> </head> <body> <h2>Processing Result:</h2> <?php $name = isset($_GET['name']) ? $_GET['name'] : 'Unknown'; $age = isset($_GET['age']) ? $_GET['age'] : 'Unknown'; echo "Name: $name<br>"; echo "Age: $age<br>"; ?> </body> </html>
We use $_GET to retrieve the transmitted name and age and display them on the page.
Through the examples above, we learned how to submit form data via POST in PHP and redirect to another page to display the results. This technique is useful for form handling, data processing, and page interaction. Mastering these methods makes PHP development more efficient and organized.