PHP Form Redirect After Submit
This guide shows you how to send a user to another page right after they submit a PHP form. You’ll learn the correct way to do it using the header() function, why it must happen before any output, and how to avoid the common pitfalls that break redirects. By the end, you’ll have a clean, working redirect that also prevents duplicate submissions.
What You’ll Need
- A web server with PHP installed (e.g., Apache, Nginx, or a local environment like XAMPP).
- A code editor to create or modify PHP files.
- A basic understanding of PHP and HTML forms.
Step-by-Step
- Create your form page. This can be a plain HTML file or a PHP file. The form’s
actionattribute should point to the PHP script that processes the form. For example:<form action="process.php" method="post"> <input type="text" name="name"> <input type="submit" value="Submit"> </form>
- Create the processing script. This is the file you pointed to in the
actionattribute (e.g.,process.php). Start the file with<?phpand do not output anything before the redirect. - Process the form data. Inside the script, handle the submitted data (e.g., validate, save to database, send an email). This is where your business logic goes.
- Call
header()to redirect. After processing, use theheader()function to send a Location header. The syntax is:<?php header('Location: success.php'); exit; ?>Replace
success.phpwith the actual URL you want to redirect to. Theexit(ordie) stops the script from continuing, which is important to prevent further output. - Make sure no output exists before
header(). Theheader()function must be called before any HTML, whitespace, or even echoes. If you have any output before it, PHP will throw a warning and the redirect will fail. This includes a UTF-8 BOM or a newline before<?php. - Test the redirect. Open your form in a browser, submit it, and confirm you land on the target page. Also check that refreshing the target page doesn’t resubmit the form (which the redirect naturally prevents).
Common Mistakes
- Output before
header(): Any HTML, echo, or even a blank line before theheader()call will cause the redirect to fail with a “headers already sent” warning. - Forgetting
exitordie: Without it, the script continues and may output content that interferes with the redirect. - Using a relative path incorrectly: While relative URLs work, it’s safer to use an absolute URL (e.g.,
https://example.com/success.php) to avoid issues with subdirectories. - Placing the redirect before processing: If you redirect before saving or validating, the form data is lost and the user never sees the result.
Tips
- Use absolute URLs: This avoids confusion when the script is in a subfolder. Example:
header('Location: https://example.com/success.php'); - Use the Post/Redirect/Get (PRG) pattern: This is exactly what you’re doing—redirect after POST to avoid duplicate submissions on refresh.
- Consider using
exitvsdie: Both work, butexitis more common and semantically clearer. - For dynamic URLs: Use
http_build_url()or concatenate variables if you need to pass data via query string, but be careful to sanitize them. - Check for PHP errors: Enable error reporting in development (
error_reporting(E_ALL); ini_set('display_errors', 1);) to see any warnings about headers.
Troubleshooting
Redirect doesn’t happen; you see a warning like “headers already sent”. This means output was sent before header(). Check for any HTML, echo, or whitespace before the PHP opening tag. Also check for a UTF-8 BOM in your file (use a text editor that shows BOM). Remove all output before the header() call.
Redirect happens but the page doesn’t load. The target URL might be incorrect or the target page has an error. Test the target URL directly in the browser. Also make sure the Location header is not followed by any output.
Form resubmits when you refresh the target page. This is a sign the redirect didn’t happen correctly. If you’re seeing a confirmation dialog, it means the browser is resending the POST request. Ensure the redirect is executed before any output and that you use exit.
Redirect works in some browsers but not others. This is rare but can happen if there’s a BOM or whitespace. Use a hex editor or a PHP linter to check for invisible characters.
You get a 404 on the target page. The URL in the Location header is wrong. Double-check the path, especially if you’re using relative URLs. Try using an absolute URL.
Frequently Asked Questions
Can I redirect to a URL with query parameters?
Yes, you can include a query string in the Location header, e.g., header('Location: success.php?name=' . urlencode($name));. Always use urlencode() for user input.
What is the difference between header('Location: ...') and using JavaScript window.location?
The PHP header() method is server-side and happens before any HTML is sent, so it’s faster and more reliable. JavaScript redirects require the page to load first and are less SEO-friendly.
Can I redirect to an external site?
Yes, you can redirect to any URL, including external ones. Just make sure the URL is fully qualified (e.g., https://example.com).
Is it possible to redirect after a delay?
Yes, but you’d need to use a meta refresh or JavaScript for a delay. PHP’s header() redirects immediately. For a delayed redirect, output a page with a meta tag like <meta http-equiv="refresh" content="5;url=success.php">.
Why do I get “Cannot modify header information” even though I have no output?
This often happens due to a UTF-8 BOM or invisible whitespace before <?php. Use a text editor that shows BOM (like Notepad++ with encoding visible) and remove it. Also check for any files included that may output content.
Should I use exit or die after header()?
Either works, but exit is more idiomatic. The important thing is to stop script execution to prevent any further output that could corrupt the redirect.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.