Click here to Skip to main content
14,739,439 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Implement a PHP function that returns a HTTP status code along with a custom message in
the header and body of the response to the client. This function will be needed for all
subsequent sections, and should be used when an error occurs (invalid input, wrong request
type etc.).

The function must set the appropriate HTTP header AND provide the message in the
response body in JSON format.

A good function definition would look like: send_error($error_code, $error_message)
The function should take 2 input parameters:
(Integer) $error_code will be the HTTP status code to return.
(String) $error_message will be a custom message text

The code variable contains a value which is also key in the $responses array provided.
This array maps integer codes with their appropriate reason text. Make sure to use this
array! You can get the server protocol from the
$_SERVER
superglobal.
The header should be of the form:
$PROTOCOL $CODE - $REASON

The response body should contain a valid JSON object of the form:
{
"error": "$CODE - $REASON: $MESSAGE"
}

Where:
$PROTOCOL = HTTP Protocol used (e.g. HTTP/1.1)
$CODE = HTTP Status Code (e.g. 400)
$REASON = HTTP Status Code Reason (e.g. "Bad Request")
$MESSAGE = Custom message (e.g. "Age must be between 13-130")
Example Header:
HTTP/1.1 400 - Bad Request: Age must be between 13-130

Example Body:
{
"error": 400 - Bad Request: Age must be between 13-130"
}

NOTE: You cannot use the
http_response_code()
function in PHP for this as it does not
allow for custom reason messages.

What I have tried:

I've tried creating a function

function send_error($error_code, $error_message){
        header("HTTP/1.1". $error_code . $error_message);
}

I think this is the wrong approach though as i keep getting an internal server error. I just don't know where to go/what to do from here
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900