The Integer vs. String Quirk in PHP Status Codes
One of the most persistent friction points in PHP HTTP development is setting response headers, specifically status codes. You often find yourself wanting to set a 404 status code generically, perhaps within a router pattern where you call something like Router::statusCode(404), expecting it to work for any valid integer from the IANA registry. However, the native header() function behaves differently than one might expect when dealing with integers versus strings.
The documentation for header() states that the third parameter can be used to specify a status code. While this sounds straightforward, there is a strict type requirement: that parameter expects a string, not an integer. Consequently, calling header('', false, 404) will fail to set the status code you intend. PHP treats the integer 404 as a truthy value in a boolean context or attempts to cast it in ways that do not result in a valid HTTP header line being sent. If you attempt this without an explicit string wrapper, the browser simply receives the default 200 OK status, potentially masking critical errors like missing resources or authorization failures.
To bypass this limitation without manually maintaining a massive array of reason phrases (e.g., mapping 403 to 'Forbidden' and 500 to 'Internal Server Error'), you must explicitly construct the status line as a string. PHP's internal handling of the third parameter is rigid; it does not automatically convert integers into their corresponding HTTP status lines like HTTP/1.1 404 Not Found. It expects the full header string or relies on the default behavior if omitted.
The solution is to combine the integer logic with a string cast. You can define a helper function that accepts an integer and converts it into the specific format header() requires. This keeps your code clean and decoupled from any manual mapping of reason phrases.
function setStatusCode(int $statusCode): void {
header("HTTP/1.1 {$statusCode}", true, $statusCode);
}
In this implementation, we pass the integer $statusCode directly to the third argument. While one might assume PHP would reject the integer here based on the "string" requirement mentioned in older docs, passing the integer after explicitly defining the header string in the first two arguments is often the key. However, strictly speaking, if you want to guarantee compatibility across different PHP versions and environments, relying on the third parameter with an integer can be risky if the underlying HTTP stream expects a specific format.
A safer, more robust approach that aligns with how modern frameworks handle this is to construct the header string using the status code integer directly in the first argument, while passing the integer as the third argument if your PHP version supports it natively. If you are targeting an environment where header('HTTP/1.1 404 Not Found', true, 404) might not work due to strict type checking on the third parameter in specific configurations, simply omitting the third parameter entirely after setting the string header is often sufficient:
header("HTTP/1.1 " . $statusCode);
// Omit the third parameter or pass the integer if your PHP version allows it
header("", true, $statusCode);
The trade-off here involves version compatibility. In older PHP versions (prior to 5.6), the third argument was strictly typed as a string in many contexts, though header() has evolved. In modern PHP 8+, type declarations are explicit, but the internal C implementation of the SAPI often accepts the integer for the status code if the header line is already defined.
If you are building a framework like Laravel or writing custom routing logic, the cleanest abstraction avoids duplicating reason phrases by leveraging the fact that the status line itself carries the weight. You do not need ['404' => 'Not Found', '500' => 'Internal Server Error'] arrays bloating your constants file. Instead, trust the HTTP spec and the ability to concatenate the integer into the header string:
function respondWithError(int $code): void {
http_response_code($code);
header("HTTP/1.1 {$code} " . get_status_text($code));
}
Wait, get_status_text() is not a standard PHP function available in the core without extension usage or custom mapping. Relying on it defeats the purpose of avoiding arrays. The most direct method that avoids external dependencies and manual mapping is to use http_response_code() followed by a header string construction if you need immediate flushing, or simply rely on http_response_code() alone if your framework handles the flushing automatically.
However, if you specifically need to force the header immediately (perhaps before any output), the most reliable pattern that avoids arrays is:
header("HTTP/1.1 {$statusCode} ", true, $statusCode);
This approach explicitly sets the status line and passes the integer as the third argument. While documentation historically emphasized strings for the third parameter, passing the integer works in modern PHP SAPIs provided the header string is present. If you encounter issues where this fails, fall back to omitting the third parameter entirely: header("HTTP/1.1 {$statusCode}"). This ensures the status code is set without requiring a lookup table of reason phrases, keeping your routing logic generic and strictly integer-based.
For more complex scenarios involving custom headers or specific content negotiation, ensure you call header() before sending any body content. The distinction between setting the status line via string concatenation versus relying solely on http_response_code() depends on when you need to flush the output buffer. If you are in a framework context, rely on the framework's response object which abstracts this underlying header() complexity, but understanding these primitives helps when debugging edge cases where standard routing fails.