HTTP requests with file_get_contents, getting the response code

file, http, php, stream

Solution

http://php.net/manual/en/reserved.variables.httpresponseheader.php

$context = stream_context_create(['http' => ['ignore_errors' => true]]);
$result = file_get_contents("http://example.com", false, $context);
var_dump($http_response_header);

Problem

I'm trying to use `file_get_contents` together with `stream_context_create` to make POST requests. My code so far: ``` $options = array('http' => array( 'method' => 'POST', 'content' => $data, 'header' => "Content-Type: text/plain\r\n" . "Content-Length: " . strlen($data) . "\r\n" )); $context = stream_context_create($options); $response = file_get_contents($url, false, $context); ``` It works fine, however, when an HTTP error occurs, it spits out a warning: ``` file_get_contents(...): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request ``` and returns false. Is there a way to: - suppress a warning (I'm planning to throw my own exception in case of failure) - obtain the error information (at least, the response code) from the stream

Original source