HTTP: headers and status codes
| Send headers | |
| Status codes that matter | |
| Redirect correctly | |
| Read the user agent |
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.
header("Content-Type: application/json"); echo json_encode(["ok" => true]);
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.
http_response_code(404); echo json_encode(["error" => "user not found"]);
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.
http_response_code(302); header("Location: /dev/php/course/39_cookies.php"); exit;
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.
$agent = $_SERVER["HTTP_USER_AGENT"] ?? "unknown"; echo $agent; if (str_contains($agent, "Mobile")) { echo "mobile view"; }
Next: Cookies
Article author: Arthur Isaev