HTTP requests with file_get_contents, getting the response code

php file_get_contents post
php file_get_contents https
file_get_contents headers
wordpress file_get_contents
file_get_contents error handling
php http header response
php http response body

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

file_get_contents("", false, ['ignore_errors' => true]);

response headers, file_get_contents() is the preferred way to read the contents of a file into a string. Example #1 Get and output the source of the homepage of a website. <?php make an http POST request and return the response content and headers You can workaround this with some extra code to request a shared lock, like <?php Home » Php » php – HTTP requests with file_get_contents, getting the response code php – HTTP requests with file_get_contents, getting the response code Posted by: admin April 10, 2020 Leave a comment

file_get_contents - Manual, Unfortunately, the drawback of using file_get_contents is that you can't retrieve HTTP response codes and error handling is extremely basic. cURL. To retrieve  I have been trying for 5 days to download an airbnb calendar on my XAMPP test site using file_get_contents, this solved the problem, thanks. – JohnnyBeGood Feb 16 '19 at 13:08 Worked for me trying to connect to Vagrant test box without a valid HTTP certificate over https.

Adding few more lines to the accepted response to get the http code

function getHttpCode($http_response_header)
        $parts=explode(' ',$http_response_header[0]);
        if(count($parts)>1) //HTTP/1.0 <code> <text>
            return intval($parts[1]); //Get code
    return 0;


to hide the error output both comments are ok, ignore_errors = true or @ (I prefer @)

Send GET request with PHP., Would like to see if file_get_contents will work. ) Here is my code. There error I am getting is "failed to open stream: HTTP request failed! This has led to the spread of insecure uses of file_get_contents() to retrieve HTTPS resources. For example, PHAR files or API requests. For example, PHAR files or API requests. Without SSL/TLS protections, all such requests are vulnerable to Man-In-The-Middle attacks where a hacker can inject a fake response, e.g. a tailored php file or json response.

I go to this page with kind of a different issue, so posting my answer. My problem was that I was just trying to suppress the warning notification and display a customized warning message for the user, so this simple and obvious fix helped me:

// Suppress the warning messages

$contents = file_get_contents($url);
if ($contents === false) {
  print 'My warning message';

And if needed, turn back error reporting after that:

// Enable warning messages again

Solved: error using PHP file_get_contents to call list_fol, The following code block checks whether the file address starts with http and In this example we're getting around Facebook's buggy IPv6 Fetching and parsing the Apache response headers for an HTTP request: <? This is a list of Hypertext Transfer Protocol (HTTP) response status codes. Status codes are issued by a server in response to a client's request made to the server. It includes codes from IETF Request for Comments (RFCs), other specifications, and some additional codes used in some common applications of the HTTP.

@file_get_contents and ignore_errors = true are not the same: the first doesn't return anything; the second suppresses error messages, but returns server response (e.g. 400 Bad request).

I use a function like this:

$result = file_get_contents(
    'http' => [
      'content' => json_encode(['value1' => $value1, 'value2' => $value2]), 
      'header' => 'Authorization: Basic XXXXXXXXXXXXXXX', 
      'ignore_errors' => 1, 
      'method' => 'POST', 
      'timeout' => 10

return json_decode($result)->status;

It returns 200 (Ok) or 400 (Bad request).

It works perfectly and it's easier than cURL.

cURL alternative to file_get_contents over HTTP < PHP, This guide shows you how to make low-level HTTP requests with the This performs a “GET” request for the URL and returns the contents. stream_context_create($opt); $response = file_get_contents($url, false, $context​); In code, we generate a unique boundary string ( -------XXXXXXX doesn't cut it​). HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: Informational responses (100–199), Successful responses (200–299), Redirects (300–399), Client errors (400–499), and Server errors (500–599).

Girders Blog PHP Guide to Making HTTP Requests, The get method returns an instance of Illuminate\Http\Client\Response the HTTP client to return empty, 200 status code responses for every request, you may  Returns a text corresponding to the status code: request: Try it: Returns the request object that requested this response: status_code: Try it: Returns a number that indicates the status (200 is OK, 404 is Not Found) text: Try it: Returns the content of the response, in unicode: url: Try it: Returns the URL of the response

HTTP Client - Laravel, PHP's file_get_contents function lets you easily fetch a URL and return the contents as a string. For HTTP GETs, REST requests take the form of a URL, so any parameters that $response = file_get_contents($request);. A complete code sample is available here. I have two Python scripts. One uses the Urllib2 library and one uses the Requests library. I have found Requests easier to implement, but I can't find an equivalent for urlib2's read() function.

PHP: Make Yahoo! Web Service REST Calls, An overview of these headers, including sample JavaScript code that initiates An HTTP/1.1 GET or a POST is used as request method. ""​) { $postData = file_get_contents('php://input'); $document In the response to the OPTIONS request, the server notifies the client that the actual  HTTP methods such as GET and POST, determine which action you’re trying to perform when making an HTTP request. Besides GET and POST, there are several other common methods that you’ll use later in this tutorial. One of the most common HTTP methods is GET. The GET method indicates that you’re trying to get or retrieve data from a

  • For those wondering, the answer to the first question is to add 'ignore_errors' => TRUE to $options.
  • @georg You can also put @ at the beginning of the line.
  • Thanks! This is an old question... I'm sure they've added something to the standard library in the meantime.
  • And how does this solve the question? Can you explain how to get the response code?
  • @Nico What do you think about my solution?
  • It's still a bad one, as you parse a JSON result not and read a random field named status - it has no connection to the HTTP status code for the API call
  • It's obvious that the RESTful API I connect to returns a JSON response and that what I need to know for my purpose (200 or 400) is contained in the "status" field. That's all I need and that's all I get. If you need to know the HTTP status code, just do this: return $http_response_header[0]; But note that it doesn't work with @file_get_contents.
  • And how does this answer the original question? Why do you think that $http_response_header[0], a highly upvoted answer, does not work with file_get_contents?