Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 790
adam78 Avatar asked Feb 19 '15 12:02

adam78


People also ask

How do you set a status code in HTTP response?

Methods to Set HTTP Status Code Sr.No. This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter.

How do I get HTTP response in PHP?

For PHP versions 4.0: In order to send the HTTP response code, we need to assemble the response code. To achieve this, use header() function. The header() function contains a special use-case which can detect a HTTP response line and replace that with a custom one. header( "HTTP/1.1 404 Not Found" );

What is Http_response_code in PHP?

The http_response_code() function sets or returns the HTTP response status code.

What is PHP status code?

Status codes are similar in that they give information about if a page has loaded successfully or not, and the root cause of any errors. PHP is a scripting language that can generate status-code data.


1 Answers

You are probably looking for...

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

header('HTTP/1.1 201 Created');
echo json_encode($arr);
like image 195
fire Avatar answered Oct 23 '22 01:10

fire