PHP http_response_code() - Set/Get Response Code
The http_response_code() function in PHP is a simple yet powerful way to control the HTTP response status code sent back to clients. Whether you want to indicate a successful request, resource not found, redirect, or server error, this function provides a straightforward method to set or retrieve the HTTP status code. This tutorial covers everything you need to know about http_response_code() with practical examples and best practices.
Prerequisites
- PHP 5.4.0 or higher (the function was introduced in this version)
- Basic knowledge of HTTP status codes (e.g., 200, 404, 500)
- Ability to run PHP scripts on a web server or local development environment
Setup Steps
- Ensure your environment is running PHP 5.4.0 or newer. You can check the PHP version by running:
php -v - Create a PHP file, e.g.,
response-code-example.php. - Add PHP code that sets or retrieves HTTP response codes using the
http_response_code()function. - Deploy the script on your server or run it locally and access it via a browser or a tool like cURL to observe the HTTP response code.
What is http_response_code()?
The http_response_code() function in PHP has two purposes:
- Set the HTTP status code to be sent with the response.
- Retrieve the current HTTP status code.
Its syntax is simple:
http_response_code([int $code]) : int|false
If you pass a status code as an argument, it sets the response code. If you call it without arguments, it returns the current response code.
Examples with Explanation
1. Setting HTTP Response Code
To set the HTTP response code, pass the desired status code as an argument:
<?php
http_response_code(404);
echo 'Page not found.';
?>
This script sends a 404 Not Found HTTP status code to the client along with the message.
2. Getting Current HTTP Response Code
Call http_response_code() without arguments to get the current status code:
<?php
$currentCode = http_response_code();
echo 'Current HTTP status code: ' . $currentCode;
?>
This returns the HTTP status code that will be or has been sent.
3. Changing HTTP Response Code Dynamically
<?php
if (!file_exists('data.txt')) {
http_response_code(404);
echo 'File not found.';
} else {
http_response_code(200);
echo 'File found and processed.';
}
?>
You can set different response codes based on your application logic, such as sending 404 when a resource is missing or 200 when everything is okay.
4. Redirecting with 301 Status Code
<?php
http_response_code(301);
header('Location: https://www.example.com/new-location');
exit;
?>
Here, the script sends a permanent redirect (301) status and sets the Location header.
Best Practices
- Always set the HTTP response code before sending any output to the browser to avoid headers already sent errors.
- Use correct and standard HTTP status codes relevant to the situation (e.g., 200 for success, 404 for not found, 500 for server error).
- Combine
http_response_code()with appropriate headers when working with redirects (301, 302). - For API responses, setting correct status codes helps clients handle errors properly.
- Test different response codes using browser developer tools or command-line like
curl -Ito verify they are correctly sent.
Common Mistakes
- Calling
http_response_code()after HTML output, causing "headers already sent" warnings. - Using invalid or non-standard HTTP status codes that browsers or clients might not recognize.
- Ignoring to exit script execution after redirects, which may cause unintended output.
- Relying on output buffering without understanding how it affects header sending.
- Not setting HTTP response code at all, leaving default 200 even on error conditions.
Interview Questions
Junior Level
-
What is the purpose of the PHP
http_response_code()function?
It is used to get or set the HTTP response status code sent by the server. -
Can
http_response_code()be used to set a 404 status code?
Yes. Callinghttp_response_code(404)sends a 404 Not Found status. -
What value does
http_response_code()return when called without parameters?
It returns the current HTTP response status code as an integer. -
From which PHP version is
http_response_code()available?
It was introduced in PHP 5.4.0. -
What happens if you set the response code after outputting HTML?
You get a "headers already sent" warning because HTTP headers must be sent before any output.
Mid Level
-
How do you use
http_response_code()for redirection?
Set the status code to 301 or 302, then send the "Location" header and exit. -
Is it mandatory to use
http_response_code()to send response codes?
No. You can use theheader()function directly, buthttp_response_code()provides a cleaner interface. -
How can you verify which HTTP status code is being sent by your PHP script?
Use browser developer tools or command-line tools likecurl -I URL. -
Does
http_response_code()affect response headers other than status?
No. It only sets or gets the HTTP status code, other headers are set withheader(). -
What is the default HTTP status code if none is set explicitly in PHP?
The default status code is 200 (OK).
Senior Level
-
Explain why it is better to use
http_response_code()instead of header("HTTP/1.1 404 Not Found")?
http_response_code()abstracts setting status codes and ensures compatibility across PHP versions and protocols. It's simpler and avoids mistakes in formatting status lines. -
How does
http_response_code()interact with output buffering in PHP?
If output buffering is enabled, headers including status codes can be set anytime before the buffer is sent; otherwise, headers must be set before output. -
What are the implications of not setting an appropriate HTTP status code in RESTful APIs?
Clients and search engines may misinterpret responses, causing improper caching, error handling, or UI behavior since status codes communicate operation results. -
How would you handle multiple response codes in the same script execution?
You should only set one HTTP response code per response; multiple calls tohttp_response_code()override previous codes. Design logic to finalize the correct code. -
Can you combine
http_response_code()with HTTP/2 or HTTP/3 protocols, and what considerations are there?
Yes,http_response_code()is protocol-agnostic at the PHP level. However, web server configuration and client support for protocols should be verified to ensure proper header transmission.
Frequently Asked Questions (FAQ)
Q1: What happens if I pass an invalid status code to http_response_code()?
PHP will accept the code but it may not be recognized or handled correctly by clients or browsers. It's best to use standard status codes.
Q2: Can I use http_response_code() to set custom HTTP status codes?
Technically yes, but itβs recommended to use only standard HTTP status codes for consistency and client compatibility.
Q3: Is it necessary to call http_response_code() before any HTML output?
Yes. HTTP status codes are part of HTTP headers, which must be sent before any body content.
Q4: Can I find a list of supported HTTP status codes for use with http_response_code()?
Yes. Refer to the HTTP Status Codes list on MDN or the official IANA registry.
Q5: Does http_response_code() send headers automatically or do I need to call header() as well?
It sends the status line with headers automatically. However, for redirects or custom headers, you still need to call header() explicitly.
Conclusion
The http_response_code() function is an essential PHP tool for setting and retrieving HTTP response codes. Correct use of HTTP status codes improves communication between your server and clients, enhancing error handling, redirection, and API behavior. By following best practices and avoiding common mistakes, you can effectively manage HTTP responses in your PHP applications.