Current Location: Home> Latest Articles> How to Implement Page Redirection After PHP Form Submission with Data Handling

How to Implement Page Redirection After PHP Form Submission with Data Handling

gitbox 2025-07-21

Basic PHP Form Submission

PHP is a popular server-side scripting language widely used for developing dynamic websites and applications. Forms are a common way to interact with users on the web by submitting data to the server for processing. This article will guide you on how to redirect to a specific page after a PHP form submission.

Creating a Simple HTML Form

First, create an HTML form where users can input information and submit it. Here's an example:

<form action="process.php" method="post">
    <input type="text" name="username" placeholder="Username"><br>
    <input type="password" name="password" placeholder="Password"><br>
    <input type="submit" value="Submit">
</form>

The form sends data using the POST method to process.php for handling.

Processing Form Data and Redirecting with PHP

In the process.php file, retrieve and handle the submitted form data with PHP. Example code:

<?php
    // Retrieve form data
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    // Add username and password validation logic here
    // ...

    // Redirect to a new page using header
    header("Location: success.php");
    exit;
?>

The header function redirects the browser to the new page success.php, and exit stops further script execution.

Creating the Success Page

After form submission, users are redirected to a success page that can display confirmation:

<h2>Submission Successful!</h2>
<?php
// Note: Use session or other methods to pass username data securely. This example is for demonstration only.
// echo "Your username is: " . htmlspecialchars($username);
?>

For security, avoid directly outputting user inputs like username and password without proper filtering and protection.

Basic Validation and Error Handling

Users may submit empty or invalid data, so validation is necessary:

<?php
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    if (empty($username) || empty($password)) {
        echo "Username and password cannot be empty.";
        echo "<a href='javascript:history.back()'>Go Back</a>";
        exit;
    }
    
    // Continue processing and redirect
    header("Location: success.php");
    exit;
?>

If validation fails, an error message is displayed with a link to return to the form.

Summary

This guide explains how to handle PHP form submission, validate input, and redirect users to another page. The process includes designing the form, retrieving data, validation, and using the header function for redirection. You can further enhance this by adding data storage, email notifications, or JavaScript for smoother user experiences.