Mastering Redirects and Header Control in PHP
Learn how to use the PHP header() function to perform redirects and manage HTTP status codes. Master control over your app's navigation and response flow.

Previously in this course, we covered Managing State with Superglobals, where we learned how to persist user data across requests. Now that you can track users, you need the ability to control where they go next. This lesson introduces the header() function, the primary tool for instructing the browser on how to handle your server's response.
Understanding HTTP Headers
When a browser makes a request to your server, your PHP script generates a response. Before any HTML content is sent to the client, the server sends a block of metadata called HTTP headers. These headers tell the browser things like:
- What type of content is being sent (e.g., text/html).
- Whether the page should be cached.
- Whether the user should be redirected to a different URL.
In PHP, you use the header() function to set these instructions. Because headers are sent before the body of your response, you must call header() before you output any HTML or even a single space character.
Performing Redirects with the Location Header
The most common use for header control is the "Redirect." When you process a form—such as saving a new post in our MVC project—you don't want the user to stay on the processing script. Instead, you want to send them to a "success" page or back to the list of items.
To redirect a user, you use the Location header.
PHP<?php #6A9955">// process_form.php #6A9955">// Imagine we just saved data to a database $success = true; if ($success) { #6A9955">// Redirect the user to the dashboard header("Location: /dashboard.php"); exit; #6A9955">// Always exit after a header redirect! }
Why use exit? Even though you sent the redirect header, the PHP script will continue to execute the remaining lines of code unless you explicitly stop it. exit ensures no further processing occurs.
Managing HTTP Status Codes
Sometimes you need to tell the browser more than just "go here." You might want to signal that a page was not found (404) or that a request was unauthorized (401). You can pass a second argument to the header() function to set the status code.
PHP<?php #6A9955">// auth_check.php $isLoggedIn = false; if (!$isLoggedIn) { #6A9955">// Send a 401 Unauthorized status code header("HTTP/1.1 401 Unauthorized"); echo "You must be logged in to view this page."; exit; }
Practical Example: Redirecting After Login
In our ongoing project, let's refine our login logic. If a user logs in successfully, we redirect them to their profile; if they fail, we send them back to the login page with an error flag.
| Header Type | Purpose | Common Code |
|---|---|---|
Location | Redirect user | header("Location: /home") |
HTTP | Define status | header("HTTP/1.1 404 Not Found") |
Content-Type | Define format | header("Content-Type: application/json") |
Hands-on Exercise
- Create a file named
redirect.php. - Inside, write an
ifstatement that checks if a variable$authorizedisfalse. - If it is
false, redirect the user toindex.phpusingheader(). - If it is
true, simply print "Welcome back!". - Test it in your browser. Ensure you see the redirect happen instantly.
Common Pitfalls
- "Headers already sent" error: This is the most common PHP error for beginners. It happens if you use
echo,print, or have HTML tags before yourheader()call. PHP needs to send the headers first; if you output content, it assumes the headers are already locked in. - Forgetting
exit: As mentioned, omittingexitallows your script to keep running. If you redirect a user to a dashboard but your script continues to query a database or output HTML, you’re wasting resources and potentially causing logic errors. - Incorrect Status Codes: Always use the standard HTTP version string (like
HTTP/1.1 404 Not Found) to ensure compatibility across all web servers.
FAQ
Q: Can I redirect to a different website?
A: Yes! Simply provide the full URL, such as header("Location: https://google.com").
Q: Does header redirection work after I've started a session?
A: Yes, session_start() does not output any content to the browser, so it is safe to call header() after starting a session.
Q: Are there security concerns with redirects? A: Be careful when redirecting based on user input. Always validate that the destination is a URL you trust to prevent "Open Redirect" vulnerabilities, where an attacker tricks a user into visiting a malicious site.
Recap
We've learned that header() is our primary mechanism for controlling the HTTP response. We use it to navigate users via Location and to communicate status via HTTP codes. Remember: always call header() before any output and pair it with exit.
Up next: We will bring these concepts together in Integrating Routing Logic, where we’ll build a central router to handle different URLs and manage 404 scenarios.
Work with me

Laravel REST API Development
Clean, secure, well-documented Laravel REST APIs — the backend engine for your app, mobile client, or SaaS. Built by an API specialist.

FilamentPHP Admin Panel & Dashboard Development
A powerful admin panel for your Laravel app — built with FilamentPHP so you can manage everything without touching the database.


