13

I have page which checks data sent via HTTP POST (http://example.com/http_post). If the data is good I add to database and wish to set http response code 201 and a success message as http response. If not I collect the errors in a an array and wish to set http response code and message as serialized JSON array as http response.

1) Whats the syntax to serialze the errors array as JSON in php?

Example

{
  "message": "The request is invalid.",
    "modelState": {
      "JobType": [ "Please provide a valid job type eg. Perm"]
  }
}
  1. Whats the syntax to set and return the http response to 412.

  2. Whats the syntax to set and return the serialized JSON in the http response body as above.

An example would be helpful on how to set all these http response headers.

Thanks

1 Answer 1

13

You are probably looking for...

$arr = array('message' => 'blah'); //etc

header('HTTP/1.1 201 Created');
echo json_encode($arr);
Sign up to request clarification or add additional context in comments.

1 Comment

As far as I can tell the array is not being returned in the response with this example, and is actually serving no purpose, or am I missing something? For me, using only <?php header('HTTP/1.1 201'); ?> produces identical response as this accepted answer, which is also identical response as using only http_response_code(402);, the difference being that header must be used at the very beginning of the file in order to work (before any output is sent).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.