PHP Headers and Output
Lesson 37 of 43 in the PHP 8 learning path.
How do I send a status and a redirect before any HTML?
header() adds a response header. It must run before any output, including a blank line or an echo.
A redirect after HTML has started cannot change the status line. The browser already has a body.
Syntax & Parameters
header('Location: /lessons', true, 302);
Example
<?php
declare(strict_types=1);
function go(string $path): never
{
if (headers_sent($file, $line)) {
throw new RuntimeException("Output started at {$file}:{$line}");
}
header('Location: ' . $path, true, 302);
exit;
}
if (($_GET['to'] ?? '') === 'catalog') {
go('/lessons');
}
echo 'Stay on this page.';
Expected Output
A request with to=catalog responds 302 and Location: /lessons. Any other request prints Stay on this page.
Line-by-Line Walkthrough
- go checks headers_sent before it writes a header.
- The thrown message names the file and line that already produced output.
- Location is a relative path on this site.
- The third argument sets status 302.
- exit stops the script so no HTML follows the redirect.
- The query to=catalog is the only trigger.
- Any other request prints a sentence.
- A space before <?php would make headers_sent true.
Common Pitfalls & Security
Check the edge before you ship it.
- A blank line before <?php sends output and blocks the redirect.
- header after echo warns and the redirect is ignored.
- A Location to a user-supplied URL is an open redirect.
- exit is required. Otherwise the script keeps printing HTML after the header.
Best Practices & Modern Standards
Send redirects before any template. Check headers_sent when you are debugging a warning.
Allow-list the destination. Do not pass a raw query string into Location.
Real-World Use
A short front script sends instructors to the catalog when they pass to=catalog, and it refuses to build a Location from an arbitrary URL.
Frequently Asked Questions
Why does PHP say headers already sent?
Some byte, even a newline, was written first. Remove it or buffer on purpose.
Does exit matter?
Yes. Without it the script continues and may append a body to the redirect.
Can Location be any site?
Do not do that. An open redirect sends people to an attacker URL.
What status should a redirect use?
302 for a temporary move after a normal GET. 303 after a POST so the next request is a GET.