0

I have a php api which is supposed to return responses with status codes. But returns only a 200 response code. This works when tested locally with Xampp but not a on live deployment server. On the deployment server i have tried :

  • header(':',true,$code);
  • http_response_code(404);
  • header("Status: 404 Not Found");
  • header('X-PHP-Response-Code: '.$code, true, $code);

Based on previous answers on stack overflow

public function echoResponse($code, $response){ 

    header(':',true,$code);  
    echo json_encode($response);
    exit();
}

I keep getting a response code of 200.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • The 200 status code means that's all ok. If there isn't any error this is the default response code that you will have in the header. What is the behavior that you expect from the api? – dwpu May 23 '19 at 17:22
  • I want my api to return a status code of 400. – Olajire Dominic May 23 '19 at 17:25
  • Did you have any error in your php error log? You can try using the `http_response_code()` function or `header("HTTP/1.0 400");`. To be sure that the header was sent, you can check it with the `headers_sent()` function. – dwpu May 23 '19 at 17:39
  • header was actually set when you echo http_response_code(); it returns the set code but the response is still sent with status code of 400 – Olajire Dominic May 23 '19 at 18:01
  • Possible duplicate of [PHP: How to send HTTP response code?](https://stackoverflow.com/questions/3258634/php-how-to-send-http-response-code) – miken32 May 23 '19 at 18:11
  • I have tried everything in the post. i have set the response code. when echoed it returns the set response but still sends back to client with status code of 200 – Olajire Dominic May 23 '19 at 18:29
  • You don't need to echo the `http_response_code()`, it will be sent automatically. – dwpu May 24 '19 at 09:08

1 Answers1

1

It should work like this: header('HTTP/1.1 500 Internal Server Error');

max
  • 23
  • 2
  • 6