PHP runs inside an HTTP exchange: a client sends a method, target, headers, and optional body; the application returns a status, headers, and body. Treat those response parts as deliberate application output rather than relying on the default 200 HTML response.
After this lesson, you can enforce an allowed request method, select a meaningful status code, send a content type before output, redirect safely, and recognize the headers-already-sent failure.
Use the method to understand the requested operation, but still validate authorization, content type, and body data. $_SERVER values originate at the server boundary and some header-derived entries remain client-controlled.
<?php
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if ($method !== 'POST') {
header('Allow: POST');
http_response_code(405);
echo 'Method not allowed';
exit;
}
A 405 response identifies the rejected method and the Allow header tells the client which method is supported.
Set status and headers before writing the body. Output from a template, included file, debug statement, or stray whitespace can make later header changes fail.
| Part | Purpose | Example |
|---|---|---|
| Status | Overall result of the request | 201 Created |
| Headers | Metadata and client instructions | Content-Type: application/json |
| Body | Representation or error details | {"id":42} |
A Location header does not stop PHP execution. Set an intentional redirect status and exit immediately so no protected or expensive work runs afterward.
<?php
header('Location: /account.php', true, 303);
exit;
A 303 tells the client to retrieve the destination with GET, which avoids resubmitting the original POST on refresh.
For production HTTP clients, prefer a maintained library or cURL with explicit timeouts, TLS verification, accepted status handling, and bounded response sizes. A remote 404 or 500 is an HTTP result, not necessarily a transport exception.
0 of 2 checked
Try this next
0 of 2 completed
Explore 500+ free tutorials across 20+ languages and frameworks.