Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 147 Β· PHP and the Web

HTTP Headers, Status Codes and Redirects

Control PHP's HTTP response: header(), http_response_code(), Location redirects, content types, downloads, caching headers and the headers already sent error.

Every response your PHP script sends has two parts. The body is what you echo: the HTML, the JSON, the CSV. Before the body comes the head: a status line saying how the request went, followed by headers that tell the browser what the body is, how long it may be cached, whether to store a cookie, or that it should go to another URL instead.

PHP fills in sensible defaults (status 200 OK, Content-Type: text/html; charset=UTF-8), so simple pages never touch the head at all. As soon as you build anything real, though, you'll need to control it: redirect after a form, answer 404 Not Found for a missing page, serve JSON or a file download, or tell browsers and CDNs how to cache.

This lesson covers header(), http_response_code(), redirects and the codes they use, content types, caching headers, security headers, and the famous "headers already sent" warning.

What a response looks like

Here is a complete HTTP response as it travels over the wire. The first line is the status line, then one header per line, then an empty line, then the body:

TEXT
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=UTF-8
Cache-Control: no-store
X-Content-Type-Options: nosniff

<!doctype html>
<title>Page not found</title>
<h1>Sorry, that page doesn't exist.</h1>

The empty line matters: it's how the browser knows the head is finished. And it explains the most important rule in this lesson: headers must be sent before any body output. Once the first byte of the body leaves the server, the head is already gone.

Status codes

The three-digit status code is the server's one-word summary of what happened. The first digit gives the class:

Range Meaning Codes you'll use most
2xx Success 200 OK, 201 Created, 204 No Content
3xx Redirection 301, 302, 303, 307, 308, 304 Not Modified
4xx The client made a mistake 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 405 Method Not Allowed, 409 Conflict, 422 Unprocessable Content, 429 Too Many Requests
5xx The server failed 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable

Picking the right code isn't pedantry. Search engines drop pages that answer 404 or 410 and keep those that answer 200, so a "page not found" message sent with 200 (a "soft 404") pollutes search results. Monitoring tools count 5xx responses to detect outages. API clients branch on the code before they even look at the body (see Building a JSON API).

Setting the code with http_response_code()

http_response_code(404) sets the status; http_response_code() with no argument returns the current one. Our editor runs PHP on the command line, which has no real HTTP response, but PHP still tracks the code you set, so you can watch it change:

PHP Setting and reading the status code

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The demo starts with ob_start() (output buffering, from PHP and HTML Templates) so the echo lines don't count as body output before the later header() calls. On a real server you'd simply set the status before printing anything. On the command line header() has nothing to send, so headers are only recorded; on a web server they become part of the response.

You may also see the status set with a raw status line, header('HTTP/1.1 404 Not Found'). It works, but it hard-codes the protocol version, while http_response_code() lets the server pick the right one (HTTP/2 and HTTP/3 have no reason phrases at all).

Sending headers with header()

header() takes one complete header line, name and value separated by a colon:

PHP
header('Content-Type: application/json');
header('Cache-Control: no-store');
header('X-Request-Id: 7f3a9c');

Its full signature is header(string $header, bool $replace = true, int $response_code = 0):

  • By default a second header() with the same name replaces the first. Pass false as the second argument to add another header with the same name instead, which some headers (like Link or Set-Cookie) need.
  • The third argument sets the status code in the same call, which is handy for redirects.

Related functions round this out: headers_list() returns the headers queued so far (on a web server; it's always empty on the command line), header_remove('X-Powered-By') removes one, and headers_sent() tells you whether it's too late to add any. Cookies have their own function, setcookie(), which also produces a Set-Cookie header.

Header injection is blocked

Headers are separated by line breaks, so a header value containing \r\n could smuggle in a second header, like a cookie or a different redirect target. That attack is called header injection (or response splitting), and PHP refuses such values outright:

PHP PHP rejects line breaks in headers

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The warning (Header may not contain more than a single header, new line detected) is the point of this example: the header is dropped and the status code stays false, meaning nothing was set. Don't rely on that safety net alone, though. Input that goes into headers should still be validated, as the safe redirect function below shows.

Redirects

A redirect is a 3xx status plus a Location header with the new URL. The browser sees it and immediately requests that URL instead:

PHP
<?php
// After saving a form: send the browser to the result page
header('Location: /orders/42', true, 303);
exit;

Always exit (or return from your controller) right after a redirect. header() doesn't stop the script. Without exit, the rest of the page still runs: it might print sensitive content that a misbehaving client reads anyway, or perform an action the redirect was meant to prevent.

Which code should you use? They differ in two ways: whether the move is permanent, and whether the browser may change a POST into a GET when it follows the redirect.

Code Meaning Method on the next request Typical use
301 Moved Permanently Permanent Browsers turn POST into GET Old URL to new URL, http to https
308 Permanent Redirect Permanent Kept exactly Permanent move of an API endpoint
302 Found Temporary Browsers usually turn POST into GET Generic temporary redirect (PHP's default)
303 See Other Temporary Always GET After a successful form POST
307 Temporary Redirect Temporary Kept exactly Temporary move that must keep the method

Permanent redirects are cached by browsers, sometimes for a very long time, so use 301/308 only when you're sure. For the classic POST-redirect-GET pattern from Handling Forms, 303 says exactly what you mean: "the POST worked; now GET this page". That way, pressing reload shows the result page instead of submitting the form again.

Safe redirects: avoid open redirects

Login pages often take a "return to" parameter: /login?next=/cart. If you redirect to whatever next contains, an attacker can send people a link to your login page that ends on their phishing site: /login?next=https://evil.example. That's an open redirect. Only redirect to paths on your own site:

PHP A redirect helper that only allows local paths

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The backslash check matters because some browsers treat /\evil.example like //evil.example. When you need to allow full URLs (to a list of partner domains, say), parse them with parse_url() or the PHP 8.5 Uri\Rfc3986\Uri class and compare the host against an allow-list instead of using string tricks.

The "headers already sent" warning

Sooner or later every PHP developer sees this:

TEXT
Warning: Cannot modify header information - headers already sent by (output started at /var/www/app/config.php:12) in /var/www/app/login.php on line 30

Read it carefully, because it tells you everything. The header() call on line 30 of login.php failed because output started at line 12 of config.php. The second location is the one to fix. The demo below triggers the warning on purpose:

PHP Triggering headers already sent on purpose

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The warning appears because the echo on line 4 started the body before header() ran. headers_sent() with two variables fills them with the place where output began, which is useful in a framework's error page. Common culprits:

  • Whitespace or a newline before <?php or after a closing ?> in an included file. This is why PSR-12 says to omit the closing tag in files that contain only PHP.
  • A UTF-8 byte order mark (BOM): three invisible bytes some editors put at the start of a file. Save files as "UTF-8 without BOM".
  • Debug output: an echo, var_dump() or a PHP warning printed to the page before the header call.
  • HTML before logic: a template printed its header and then tried to redirect.

The real fix is structure: decide on the status, headers and redirects first, then produce the body. Turning on output_buffering in php.ini hides the problem (the body is held back in a buffer, so headers can still be added), but it doesn't fix the design, and it breaks as soon as the buffer fills up or someone flushes it.

Content types and downloads

Content-Type tells the browser how to interpret the body. PHP's default is text/html; charset=UTF-8. Change it whenever you send anything else:

Body Header
HTML page Content-Type: text/html; charset=UTF-8
JSON Content-Type: application/json
Plain text Content-Type: text/plain; charset=UTF-8
CSV Content-Type: text/csv; charset=UTF-8
PDF Content-Type: application/pdf
Unknown binary data Content-Type: application/octet-stream

To make the browser save the body as a file instead of displaying it, add Content-Disposition: attachment with a file name. Since the editor can't show real headers, the next demo uses a tiny response recorder that prints what a server would send. It's a simulation of the HTTP response, but the CSV body is produced exactly as a real script would produce it:

PHP A CSV download, printed as raw HTTP

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

On a real server you'd replace the Response object with three header() calls followed by echo. Content-Length is the size in bytes (strlen(), not mb_strlen()), which is why "BjΓΆrn" counts one extra byte for the ΓΆ. CSV writing is covered in CSV Files.

For big files, don't load everything into memory: send the headers, then stream the file with readfile($path) or a loop over fread(). And never build the path from user input without validation (see Secure Coding Checklist).

Caching headers

Caching makes sites fast, and the response headers control it. Cache-Control is the main one:

Header value Meaning
Cache-Control: no-store Never store this response (account pages, anything personal)
Cache-Control: private, max-age=60 Only the user's browser may cache it, for 60 seconds
Cache-Control: public, max-age=3600 Browsers and shared caches (CDNs) may cache it for an hour
Cache-Control: no-cache May be stored, but must be revalidated with the server before each use
Cache-Control: public, max-age=31536000, immutable Versioned assets such as app.3f9c1e.css that never change

Note that no-cache doesn't mean "don't cache"; no-store does. Also note that session_start() sends Cache-Control: no-store, no-cache, must-revalidate by default (the session.cache_limiter = nocache setting), because pages that use a session are usually personal.

Conditional requests and 304 Not Modified

A server can label a response with a validator: an ETag (a fingerprint of the content) or a Last-Modified date. Next time, the browser asks "has it changed?" by sending If-None-Match with the ETag. If nothing changed, the server answers 304 Not Modified with no body at all, saving the bandwidth. PHP sees request headers in $_SERVER with an HTTP_ prefix (see Superglobals), so the demo fills that array to simulate two browser requests:

PHP ETag and 304 Not Modified

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Cache-Control: no-cache plus an ETag gives you the best of both: the browser always checks, but most checks cost only a tiny 304. In production, a CDN like Cloudflare or a reverse proxy like nginx can do this for you, which is why getting Cache-Control right on public pages pays off so much. The performance lesson covers caching inside PHP itself.

Security headers

A handful of headers make browsers enforce extra protections. They cost nothing and belong on every HTML response, usually set once in a front controller (Front Controllers and Routing) or in the web server config:

PHP
header('X-Content-Type-Options: nosniff');                  // don't guess content types
header('Referrer-Policy: strict-origin-when-cross-origin'); // share less in the Referer header
header("Content-Security-Policy: default-src 'self'; frame-ancestors 'none'");
header('Strict-Transport-Security: max-age=31536000; includeSubDomains'); // HTTPS only
header_remove('X-Powered-By');                              // don't advertise the PHP version

Content-Security-Policy is a strong defense against XSS and gets its own section in Preventing XSS. frame-ancestors 'none' stops other sites from embedding yours in a frame (clickjacking). X-Powered-By: PHP/8.5.8 is added when expose_php is on; switching it off in php.ini is cleaner than removing the header in code.

You'll sometimes see Expires, Pragma: no-cache and X-XSS-Protection in old code. Cache-Control replaced the first two long ago, and modern browsers ignore X-XSS-Protection; use a Content-Security-Policy instead.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. Your script calls header('Location: /done'); and nothing else. What status code does PHP send?

    A Location header changes the status to 302 Found unless you already set a 201 or 3xx code. Pass a third argument (303, 301, ...) to choose the code yourself.
  2. 2. Why should a redirect be followed by exit?

    header() only queues the header. Without exit, the remaining code still executes and may print or do things the redirect was meant to prevent.
  3. 3. A warning says: headers already sent by (output started at /app/config.php:12) in /app/login.php on line 30. Where is the problem?

    The output-started location is where the body began. Fix that output (often stray whitespace, a BOM or debug output) or restructure the code so headers are set first.
  4. 4. Which status code fits best after a successful form POST that redirects to a result page?

    303 tells the browser to load the result with GET, so reloading the page doesn't resubmit the form. 301 is permanent and gets cached.
  5. 5. What does Cache-Control: no-cache mean?

    no-cache means "check with me first". To forbid storing a response, use no-store.

Summary

  • A response is a status line, headers, an empty line and a body. Headers must be sent before any body output.
  • Set the status with http_response_code(404) and headers with header('Name: value'). The second argument of header() controls replacing; the third sets the status code.
  • Redirect with header('Location: /path', true, 303); exit;. Use 303 after form posts, 301/308 only for permanent moves, and only redirect to validated local paths to avoid open redirects.
  • "Headers already sent" names the place where output started: stray whitespace, a BOM, a closing ?> or debug output. Fix the structure instead of hiding it with output buffering.
  • Set Content-Type for anything that isn't HTML, and Content-Disposition: attachment for downloads. Content-Length counts bytes.
  • Cache-Control decides who may cache a response and for how long; ETags with 304 Not Modified make revalidation cheap. Add security headers such as X-Content-Type-Options and Content-Security-Policy to every page.

Next: Front Controllers and Routing