How to Send HTTP Response Codes in PHP
In a standard PHP script, the output buffer often handles what happens after your logic finishes executing. However, when you need to explicitly signal an error condition, a redirect, or a specific server status like 200 OK or 404 Not Found, you must intervene directly with the HTTP layer. The primary mechanism for this is the http_response_code() function.
This function allows you to set the status line of the HTTP response without altering the body content immediately. You can invoke it anywhere in your script before headers are sent, but usually, it is best placed near the top of your logic or at the very end after all rendering is complete.
<?php
// Set the status code
http_response_code(403);
// Optionally send a custom reason phrase
header("HTTP/1.1 403 Forbidden");
// The body content will follow
echo "Access denied.";
?>
While http_response_code() is convenient, it operates on the current header state. If you have already called echo or print, PHP has started sending output, and headers can no longer be modified. Attempting to set a status code after output begins results in a "Headers already sent" warning, which often indicates a deeper issue like whitespace before the opening < tag or an included file containing accidental newlines.
Handling Redirects with Headers
When you need to redirect a user, relying solely on http_response_code(302) is insufficient if you intend for the browser to actually follow the link. A 302 status code changes the response line, but without setting the Location header, browsers typically treat it as a standard response rather than a navigation instruction.
To perform a proper redirect, you must combine the status code with the Location header and then explicitly terminate the script execution. This prevents PHP from rendering any further HTML or outputting whitespace that would break the redirect chain.
<?php
// Set the 302 Found status
http_response_code(302);
// Define where to send the client
header('Location: https://example.com/new-page');
// Terminate immediately
exit;
?>
The exit statement is critical here. If you omit it, PHP continues executing subsequent lines in the file. Any echo statements or template rendering after the redirect will result in a double-content error, where you see both the original page and the destination URL printed to the screen. This breaks the user experience and confuses browser caching mechanisms.
Custom Reason Phrases and Standards
By default, PHP uses standard reason phrases like "OK", "Not Found", or "Forbidden" when you pass a numeric code to http_response_code(). While these are technically correct per RFC 7231, modern web development often benefits from customizing the reason phrase for clarity. You can do this by constructing the raw HTTP header string manually using header().
<?php
// Custom status line with a specific reason phrase
header('HTTP/1.1 400 Bad Request');
// Or combine them if your framework allows it
http_response_code(400);
header("X-Custom-Header: Something went wrong");
?>
It is important to note that once you modify headers or send output, the status line cannot be changed again. If you call http_response_code() multiple times, only the last value sent before output begins takes effect. This limitation means you must plan your header logic carefully, especially when integrating with third-party libraries that might emit debug messages or error logs unexpectedly.
Framework Considerations
If you are working within a modern framework like Laravel, the manual manipulation of http_response_code() is often unnecessary for standard HTTP verbs. Laravel's request lifecycle automatically maps GET requests to 200 responses and handles redirects via helper functions like redirect(). However, understanding the underlying mechanics remains essential when debugging status code issues or building custom middleware.
For robust handling of these scenarios in larger applications, utilizing a dedicated package designed for API development can streamline response management. Resources such as LaravelCompany often discuss best practices for maintaining strict adherence to RESTful standards, ensuring that your application returns the correct status codes without manual intervention unless specifically required by custom logic.
Ultimately, mastering HTTP response codes in PHP requires respecting the order of operations: set the code and headers first, then output content, and finally terminate the script if a redirect is involved. Ignoring these rules leads to inconsistent behavior across different browsers and caching layers.
