Home > Backend Development > PHP Tutorial > How to Retrieve HTTP Response Codes from `file_get_contents` POST Requests?

How to Retrieve HTTP Response Codes from `file_get_contents` POST Requests?

Patricia Arquette
Release: 2024-12-04 07:16:14
Original
813 people have browsed it

How to Retrieve HTTP Response Codes from `file_get_contents` POST Requests?

Retrieving Response Codes in HTTP Requests Using file_get_contents

When making POST requests using file_get_contents with stream_context_create, users may encounter HTTP errors that generate warnings. To mitigate this and obtain the response code for error handling, follow these steps:

Suppress Error Warnings

Use the ignore_errors option in stream_context_create to suppress the warnings:

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

Retrieve Response Code

The HTTP response code is stored in the $http_response_header PHP variable after executing file_get_contents. Use var_dump() to view the headers, where the first element contains the response status (e.g., "HTTP/1.0 400 Bad Request").

Example

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

var_dump($http_response_header); // Display response headers, including response code
Copy after login

The above is the detailed content of How to Retrieve HTTP Response Codes from `file_get_contents` 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