adam78
adam78

Reputation: 10078

How to set http response status code and message in php

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

Upvotes: 13

Views: 24011

Answers (1)

fire
fire

Reputation: 21531

You are probably looking for...

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

header('HTTP/1.1 201 Created');
echo json_encode($arr);

Upvotes: 13

Related Questions