Advertisement
Category: PHP 02/04/2022 DarkIntaqt

How to get the PHP file_get_contents() status code

The http_respone_header variable explained

The file_get_contents() function in php is pretty useful to easily request a file from another server or same server/computer.

It is pretty simple to get the status code of a file_get_contents() request.

This does not work on local request, http and https requests only!

The revered variable $http_response_header contains the status code of the request, but always only from the last one.

<?php

	$request = file_get_contents("https://darkintaqt.com");
	$http_response_header; // For $request, because it was the last one

?>

$http_response_header is an array and the first index is always the status code.

<?php

	$request = file_get_contents("https://darkintaqt.com");

	echo $http_response_header[0]; // Output: HTTP/2 200 OK

?>

Some are satisfied with this result, but you can just get the status code as a number.

<?php

	$request = file_get_contents("https://darkintaqt.com");

	preg_match('/([0-9])\d+/',$http_response_header[0],$matches);

	$responsecode = intval($matches[0]);

	echo $responsecode; // Output: 200

?>
Advertisement

Tip

To avoid errors and warnings in the case of bad status codes, you can place an @ in front of the file_get_contents so that this does not throw any errors.

<?php

	$request = @file_get_contents("https://darkintaqt.com");

	preg_match('/([0-9])\d+/',$http_response_header[0],$matches);

	$responsecode = intval($matches[0]);

	echo $responsecode; // Output: 200

?>
About The Author
"DarkIntaqt is a web developer from Germany who has been programming websites since 2017. He always has tips and tricks for JavaScript and PHP and unfortunately a weakness for League of Legends and biscuits."

DarkIntaqt's Website

Table of contents

Tip

Advertisement