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

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

Linda Hamilton
Release: 2024-12-03 12:12:16
Original
959 people have browsed it

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

Getting the HTTP Response Code from HTTP Requests Using file_get_contents

When utilizing file_get_contents for POST requests with stream_context_create, you may encounter HTTP errors and warnings. This article explores methods to handle these errors effectively.

To suppress the warning, you can set the 'ignore_errors' key to true within the 'http' options array of stream_context_create, as seen below:

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

This eliminates the warnings and allows you to proceed with your own exception handling logic.

To retrieve the response code, you can utilize the $http_response_header variable, which is populates with the response headers upon execution of file_get_contents:

var_dump($http_response_header);
Copy after login

By accessing this variable, you can obtain detailed information about the HTTP response, including the response code and other headers.

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