Home > Backend Development > PHP Tutorial > How Can I Handle HTTP Errors and Retrieve Response Codes When Using `file_get_contents` for POST Requests?

How Can I Handle HTTP Errors and Retrieve Response Codes When Using `file_get_contents` for POST Requests?

Barbara Streisand
Release: 2024-12-21 22:48:28
Original
233 people have browsed it

How Can I Handle HTTP Errors and Retrieve Response Codes When Using `file_get_contents` for POST Requests?

HTTP Requests with file_get_contents: Retrieving Response Codes

When sending POST requests using file_get_contents and stream_context_create, error handling can be challenging. The code snippet provided demonstrates the basics of POST requests with file_get_contents, but it suffers from two limitations:

  • It displays an error warning when an HTTP error occurs.
  • It provides no way to obtain the HTTP error code.

To address these limitations, consider the following solutions:

Suppressing Error Warnings

To suppress the unwanted warning, you can use the 'ignore_errors' option in the stream context:

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

By enabling this option, file_get_contents will not display an error warning on HTTP errors and instead return a 'false' value, indicating a failed request.

Retrieving HTTP Response Codes

To obtain the HTTP response code, you can utilize the PHP superglobal variable $http_response_header, which becomes populated when using file_get_contents with a stream context. After you have suppressed the error warning, you can access the response code by using the following code:

$result = file_get_contents("http://example.com", false, $context);
var_dump($http_response_header);
Copy after login

This will output the HTTP response headers, including the response code.

By implementing these solutions, you can enhance your code's ability to handle HTTP errors while making POST requests using file_get_contents and stream_context_create.

The above is the detailed content of How Can I Handle HTTP Errors and Retrieve Response Codes When Using `file_get_contents` for POST Requests?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template