How to send HTTP response codes in PHP API?
18
I'm building a PHP API and need to send proper HTTP response codes like 200 OK, 404 Not Found, or 500 Internal Server Error.
What's the correct way to set HTTP status codes in PHP? I want to ensure my API follows REST conventions properly.
1 Answer
25
In PHP, you can set HTTP response codes using the `http_response_code()` function. Here's how to implement it properly:
### Basic Usage
```php
```
### Common HTTP Status Codes for APIs
- **200 OK** - Successful GET, PUT, PATCH requests
- **201 Created** - Successful POST request that creates a resource
- **204 No Content** - Successful DELETE request
- **400 Bad Request** - Invalid request data
- **401 Unauthorized** - Authentication required
- **403 Forbidden** - Access denied
- **404 Not Found** - Resource not found
- **422 Unprocessable Entity** - Validation errors
- **500 Internal Server Error** - Server error
### API Response Example
```php
'success', 'data' => $user]);
} else {
http_response_code(404);
echo json_encode(['status' => 'error', 'message' => 'User not found']);
}
?>
```
**Note:** Always set the response code before outputting any content, and consider setting appropriate headers like `Content-Type` for APIs.