Home >Backend Development >PHP Tutorial >How to Handle HTTP Errors and Retrieve Response Codes with `file_get_contents` and `stream_context_create`?

How to Handle HTTP Errors and Retrieve Response Codes with `file_get_contents` and `stream_context_create`?

Linda Hamilton
Linda HamiltonOriginal
2024-12-02 08:17:10759browse

How to Handle HTTP Errors and Retrieve Response Codes with `file_get_contents` and `stream_context_create`?

HTTP Response Code with file_get_contents and stream_context_create

In order to make POST requests, you can utilize file_get_contents in conjunction with stream_context_create. However, you may encounter warnings when you encounter HTTP errors. This article addresses this issue and provides solutions for both suppressing the warnings and obtaining response codes from the stream.

To begin, consider the following scenario:

$options = ['http' => [
    '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);

This code handles POST requests, but in the event of an HTTP error, a warning is displayed:

file_get_contents(...): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

Additionally, it returns false. Two concerns arise from this issue:

  1. Can I prevent the warning from appearing?
  2. Is it possible to retrieve error details, particularly response codes, from the stream?

Suppressing the Warning

To suppress the warning, we can utilize the ignore_errors option within stream_context_create():

$context = stream_context_create(['http' => ['ignore_errors' => true]]);

With this modification, the warning will no longer be displayed.

Obtaining Response Codes

To obtain the response code from the stream, you can inspect the http_response_header variable:

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

This code will display an array containing response headers, including the response code.

The above is the detailed content of How to Handle HTTP Errors and Retrieve Response Codes with `file_get_contents` and `stream_context_create`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn