Home > Backend Development > PHP Tutorial > How Can I Retrieve HTTP Response Codes Using `file_get_contents` and `stream_context_create`?

How Can I Retrieve HTTP Response Codes Using `file_get_contents` and `stream_context_create`?

Susan Sarandon
Release: 2024-12-01 21:53:12
Original
249 people have browsed it

How Can I Retrieve HTTP Response Codes Using `file_get_contents` and `stream_context_create`?

Retrieving HTTP Response Code with file_get_contents and stream_context_create

When utilizing file_get_contents and stream_context_create for POST requests, handling HTTP errors is crucial. By default, file_get_contents raises warnings when encountering HTTP errors, making it difficult to retrieve the response code.

To suppress these warnings and obtain the response code, you can leverage the following solution:

Suppressing Warnings and Retrieving Response Code

  1. Create a stream context using stream_context_create with the following options:
$options = [
    'http' => [
        'ignore_errors' => true
    ]
];
Copy after login

The 'ignore_errors' option suppresses warnings generated by file_get_contents.

  1. Utilize file_get_contents with the created stream context to retrieve the response:
$result = file_get_contents("http://example.com", false, $context);
Copy after login
  1. After retrieving the response with file_get_contents, the HTTP response header information, including the response code, will be available in the global $http_response_header variable. You can access the response code as follows:
var_dump($http_response_header);
Copy after login

This technique allows you to handle HTTP errors gracefully without warnings and retrieve the response code from the stream.

The above is the detailed content of How Can I Retrieve HTTP Response Codes Using `file_get_contents` and `stream_context_create`?. 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