-1

I'm getting 400 response code for an HTTP request. I want to read the response message in PHP. I'm reading response code like this:

$options = array(
            'http' => array(
                'header'  => "Content-type: application/json\r\n",
                'method'  => 'POST',
                'content' => json_encode($data)
                ),
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
                ),
            );
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        if(strrpos($http_response_header[0], '200')){
            echo '200'."<br/>";
            return $result;
        }
        elseif(strrpos($http_response_header[0], '400')){
            echo '400'."<br/>";
            return $result;
        }

I'm getting result = bool(false) in the case of response code 400.

Cœur
  • 37,241
  • 25
  • 195
  • 267
DesiHacker
  • 108
  • 2
  • 15

2 Answers2

0

Try this

if (http_response_code() == 400)
    return true;
0

Try to add to 'ignore_errors' => true Your http options in context :

$options = array(
        'http' => array(
            'header'  => "Content-type: application/json\r\n",
            'method'  => 'POST',
            'content' => json_encode($data),
            'ignore_errors' => true
            ),
        "ssl"=>array(
            "verify_peer"=>false,
            "verify_peer_name"=>false,
            ),
        );
bigwolk
  • 418
  • 4
  • 17
  • I don't want to read the 'response code message.' I know that this request is returning a json string in response body which I can via POST Man, But I have to read this (response body) in PHP. – DesiHacker Apr 16 '18 at 08:15
  • So question is wrong. There won't be any response body - Your request is wrong and server can't read this. – bigwolk Apr 16 '18 at 08:18
  • There is response body which I can see by hitting the same request from POSTMan Client. – DesiHacker Apr 16 '18 at 08:20
  • I updated the question with more code. Please check – DesiHacker Apr 16 '18 at 08:20
  • I've edited my answer - it should help to You according to [documentation](http://php.net/manual/en/context.http.php), but in case of error (400) server shouldn't return any response - response code should be Your answer. – bigwolk Apr 16 '18 at 08:26