PHP - REST API - http headers - error handling

2019-07-31 23:17发布

I am trying to return a HTTP header together with XML stating whether a process has been successful or not.

This all appeared to be working fine whilst developing my API, I was making test calls to the API from the same server and getting the relevant header status code together with the XML. However, when I test this again but calling the API from other server and am encountering a problem.

If the response is 200 then I get the response XML. If there is an error, I receive the header status code OK but get no error XML. I have played around wit the the error messaging function and noticed that if I comment out header($status_header); the error XML is sent. Can anyone shed some light as to why this might be happening?

    static function errorResponse($status = 400, $body = '')  {  

    $status_message = APIResponse::getStatusCodeMessage($status);
            $status_header = 'HTTP/1.1 ' . $status . ' ' . $status_message;  

    // set the HTTP status  
    header($status_header);   

    if($body == '')  {  
       // create the message if none is passed  
      $body = '';  

      switch($status)  
      {  
          case 401:  
              $body = 'You must be authorized to view this page.';  
              break;  
          case 404:  
              $body = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';  
              break;  
          case 500:  
              $body = 'The server encountered an error processing your request.';  
              break;  
          case 501:  
              $body = 'The requested method is not implemented.';  
              break;  
      }  

    } 

      $response_xml = '<?xml version="1.0" encoding="utf-8"?> 
          <error>  
              <date>' . date("D, d M Y H:i:s", time()) . '</date>
              <status>' . $status . ' - ' . $status_message . '</status> 
              <message><![CDATA[' . $body . ']]></message> 
          </error>';  

      return $response_xml;  
      exit;  

}  

1条回答
▲ chillily
2楼-- · 2019-07-31 23:45

I've now sorted this, it was an error with my class containing CURL functions, nothing to do with this class.

查看更多
登录 后发表回答