PHP 8 Intermediate HTTP & Files · 6 min read

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

Syntax
header('Location: /lessons', true, 302);

Example

public/go.php
<?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

  1. go checks headers_sent before it writes a header.
  2. The thrown message names the file and line that already produced output.
  3. Location is a relative path on this site.
  4. The third argument sets status 302.
  5. exit stops the script so no HTML follows the redirect.
  6. The query to=catalog is the only trigger.
  7. Any other request prints a sentence.
  8. 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.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…