How to get the status code of file_get_contents in PHP
The file_get_contents() function in PHP is pretty useful to easily request a resource from another server or locally.
Keep in mind that this only works for HTTP and HTTPS request and not when opening a file on your own system!
Get the status
The reserved PHP variable $http_response_header always contains the status code of the request.
<?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 with all headers and also the status code. The status code is always the first index in the variable.
<?php
$request = file_get_contents("https://darkintaqt.com");
echo $http_response_header[0]; // Output: "HTTP/2 200 OK"
?>
Get the status code
Now we have an string as an output. We surely can better and extract only the status code as a number using this code snippet:
<?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
?>
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
?>