HTTP: headers and status codes

An HTTP response is a status line, a few headers and a body. In PHP the script sends all three, and the browser or the API client decides what happened from the status and the headers before it reads the body.

Send headers

The header() function sends one raw HTTP header. Call it before any output, including spaces and error messages, or PHP reports headers already sent.

Use headers to declare content type, caching rules, and download names.

The file headers.php in the folder you serve with php -S 127.0.0.1:8000:

<?php header("Content-Type: application/json"); echo json_encode(["ok" => true]);

curl -s "http://127.0.0.1:8000/headers.php"

{"ok":true}

The body is JSON and the header tells the client how to read it, so a program does not have to guess from the text. json_encode() builds the body from the array.

Status codes that matter

Browsers and APIs decide what happened from the status code, not from the body text. Set it explicitly with http_response_code for errors and empty answers.

Learn five codes first: 200 for success, 201 for created, 400 for bad input, 404 for missing, and 500 for server failure.

The file status.php in the same folder:

<?php http_response_code(404); echo json_encode(["error" => "user not found"]);

curl -s "http://127.0.0.1:8000/status.php"

{"error":"user not found"}

The body names the error and the status line of the response is 404, checked with a client that reads it. A client that only looked at the body would miss the difference between this answer and a successful one with a similar text.

Redirect correctly

A redirect is a Location header plus a 3xx status. Send both, then stop the script so no extra output leaks after the redirect.

Use 302 for temporary moves after form posts and 301 only for permanent address changes.

The file redirect.php in the same folder:

<?php http_response_code(302); header("Location: /dev/php/course/045_cookies.php"); exit;

The response carries the 302 status and the Location header, and the script stops before anything else can print. A client that follows the redirect asks for the cookie lesson next; the request was checked with a client that follows the header, and the page itself shows no body.

Read the user agent

Browsers send a user agent string that names the client. Read it from the server array when you need device specific output or simple bot detection. See Check your HTTP_USER_AGENT and How to get screen size with PHP.

Never trust it for security decisions, since any client can send any string.

The file agent.php in the same folder:

<?php $agent = $_SERVER["HTTP_USER_AGENT"] ?? "unknown"; echo $agent; if (str_contains($agent, "Mobile")) { echo "mobile view"; }

curl -s -A "Mozilla/5.0 (Mobile)" "http://127.0.0.1:8000/agent.php"

Mozilla/5.0 (Mobile)mobile view

The script echoes the string it received and adds the mobile line, because str_contains() finds the word inside it. A client that sends another string gets its own text back and no extra line.

Exercises

  1. Change headers.php to send a text/plain header and request it again. What does the body look like now?
  2. Answer status.php with 201 instead of 404 and read the status line of the response.
  3. Send a user agent without the word Mobile and run agent.php against it.
  4. Print something before the header call in headers.php and read the warning.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What must be true before header() is called?

    Answer

    No output has been sent yet

    A header belongs to the response head, so PHP cannot send it after the first byte of the body.

  2. Which status code says the resource does not exist?

    Answer

    404

    404 Not Found is the code for a missing resource; 500 is a server failure.

  3. Which status code fits a permanent move to a new address?

    Answer

    301

    301 Moved Permanently tells clients and search engines to use the new address from now on.

  4. What should follow the Location header of a redirect?

    Answer

    The exit statement, so the script stops

    Without exit the rest of the script still runs and may print into the response of the redirect.

  5. What does this program print? <?php header("Content-Type: application/json"); echo json_encode(["ok" => true]);

    Answer

    {"ok":true}

    json_encode turns the array into a JSON object, and a boolean true becomes true in the text.

  6. What does this program print? <?php $agent = "Mozilla/5.0 (Mobile)"; echo $agent; if (str_contains($agent, "Mobile")) { echo "mobile view"; }

    Answer

    Mozilla/5.0 (Mobile)mobile view

    The agent string prints first and the check then adds its own line without a space.

  7. What does this program print? <?php http_response_code(404); echo http_response_code();

    Answer

    404

    The first call sets the status and the second one reads it back.

  8. What does this program print? <?php echo json_encode(["error" => "user not found"]);

    Answer

    {"error":"user not found"}

    Both the key and the string value are quoted in JSON, and the object keeps the key.

  9. Why is the user agent unsafe for a security decision?

    Answer

    Any client can send any string it likes

    The header is written by the client, so a script or an attacker can claim to be anything.

  10. Which header tells the client that the body is JSON?

    Answer

    Content-Type: application/json

    Content-Type describes the body that follows, and the client picks its parser from it.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev