How to Redirect Users After Form Submission in PHP

Last updated 1 month ago | 98 views 75     5

Tags:- PHP

Redirecting users to a new page after form submission while sending the data via email is a common task in web development. This guide will show you the correct approach to achieve this using PHP.

✅ PHP Code for Form Handling and Redirection

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Collect form data
    $name = $_POST['name'] ?? '';
    $email = $_POST['email'] ?? '';
    $message = $_POST['message'] ?? '';

    // Validate the input (optional but recommended)
    if (empty($name) || empty($email) || empty($message)) {
        die("All fields are required.");
    }

    // Send the email
    $to = "[email protected]"; // Replace with your email
    $subject = "Contact Form Submission";
    $body = "Name: $name\nEmail: $email\nMessage: $message";
    $headers = "From: $email";

    if (mail($to, $subject, $body, $headers)) {
        // Redirect to a thank-you page after successful submission
        header("Location: thank-you.html");
        exit(); // Prevent further script execution
    } else {
        echo "Email sending failed. Please try again.";
    }
}
?>

Explanation

  1. Check the request method: Ensures the form is submitted via POST.

  2. Collect and validate form data: Basic validation prevents empty submissions.

  3. Send the email: Using the mail() function.

  4. Redirect with header(): Redirects to thank-you.html after successful form submission.

  5. Use exit(): Stops script execution after the redirect.

✅ HTML Form

<form action="form-handler.php" method="post">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required><br>

  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required><br>

  <label for="message">Message:</label>
  <textarea id="message" name="message" required></textarea><br>

  <button type="submit">Submit</button>
</form>

Important Tips

  • Place the header() function before any HTML output.

  • Use exit() after the header() to stop script execution and avoid issues with further code execution.

  • Handle errors gracefully to give feedback to the user.

By following this approach, you can efficiently handle form submissions while redirecting users to a confirmation or thank-you page.