Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Send HTTP Response Code in PHP
In PHP, you can send HTTP response codes to communicate the status of a request to the client. This is essential for proper web communication and helps browsers, APIs, and other clients understand how to handle the response.
Using http_response_code() Function
The http_response_code() function is the simplest method to set HTTP response codes in PHP 5.4+:
<?php // Set successful response http_response_code(200); // Set not found response http_response_code(404); // Set server error response http_response_code(500); ?>
This function must be called before any output is sent to the client. You can also retrieve the current response code by calling it without parameters:
<?php http_response_code(404); echo "Current response code: " . http_response_code(); // Outputs: 404 ?>
Using header() Function
The header() function provides more control and works in all PHP versions:
<?php
// Method 1: Full status line
header("HTTP/1.1 404 Not Found");
// Method 2: Using the third parameter
header("Location: /login", true, 302);
// Method 3: Setting just status
header("Status: 503 Service Unavailable");
?>
The third parameter in header() allows you to set the response code directly, which is useful when redirecting or setting other headers.
Common Response Codes
| Code | Status | Use Case |
|---|---|---|
| 200 | OK | Successful request |
| 404 | Not Found | Resource not found |
| 500 | Internal Server Error | Server error occurred |
| 302 | Found | Temporary redirect |
Practical Example
Here's a practical example of using response codes in a simple router:
<?php
$page = $_GET['page'] ?? 'home';
switch($page) {
case 'home':
http_response_code(200);
echo "Welcome to homepage";
break;
case 'admin':
http_response_code(403);
echo "Access forbidden";
break;
default:
http_response_code(404);
echo "Page not found";
}
?>
Key Points
Response codes must be set before any output is sent
Use
http_response_code()for PHP 5.4+ (recommended)Use
header()for older PHP versions or more controlAlways choose appropriate codes based on the actual response status
Conclusion
Setting proper HTTP response codes is crucial for web communication. Use http_response_code() for simplicity or header() for more control, ensuring codes are set before any output is sent to the client.
