Get Last HTTP Response Headers in PHP 8.4

Get Last HTTP Response Headers in PHP 8.4

PHP provides an HTTP wrapper that enables access to files over HTTP. For instance, the file_get_contents function can retrieve both remote files via HTTP and local files from the file system.

After successfully establishing a remote connection, the HTTP wrapper populates the $http_response_header local variable with the HTTP response headers.

<?php

file_get_contents('https://httpbin.org/get');

var_dump($http_response_header);

A part of the output:

array(8) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Tue, 10 Dec 2024 16:36:15 GMT"
  [2]=>
  string(30) "Content-Type: application/json"
...
}

Since PHP 8.4, we can use the http_get_last_response_headers function for retrieving last HTTP response headers received via the HTTP wrapper. If there is no HTTP response, null is returned instead. This function can be used as an alternative to the $http_response_header variable.

<?php

file_get_contents('https://httpbin.org/get');

var_dump(http_get_last_response_headers());

Starting with PHP 8.4, the http_clear_last_response_headers function can be used to clear the HTTP response headers received through the HTTP wrapper.

<?php

file_get_contents('https://httpbin.org/get');

var_dump(http_get_last_response_headers()); // array(8) { ... }
http_clear_last_response_headers();
var_dump(http_get_last_response_headers()); // null

Leave a Comment

Cancel reply

Your email address will not be published.