Hi,
You can simply get the response code from the headers sent by the server in response to a HTTP request. To get the headers information, you can use $http_response_header or get_headers(). These functions will return a similar array:
[0] => HTTP/1.0 200 OK
[1] => Age: 456666
[2] => Cache-Control: max-age=604800
[3] => Content-Type: text/html; charset=UTF-8
[4] => Date: Fri, 05 Apr 2024 16:52:22 GMT
[5] => Etag: "3147526947+ident"
[6] => Expires: Fri, 12 Apr 2024 16:52:22 GMT
[7] => Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT
[8] => Server: ECS (nyd/D146)
[9] => Vary: Accept-Encoding
[10] => X-Cache: HIT
[11] => Content-Length: 1256
[12] => Connection: close
Get HTTP response code with $http_response_header:
$content = file_get_contents("https://example.com");
$response_header = $http_response_header;
if ( preg_match("/\s([0-9]{3})\s/i", $response_header[0], $t) ) { $response_code = $t[1]; }
else { $response_code = "no response code"; }
echo $response_code;
Get HTTP response code with get_headers():
$response_header = get_headers("https://example.com");
if ( preg_match("/\s([0-9]{3})\s/i", $response_header[0], $t) ) { $response_code = $t[1]; }
else { $response_code = "no response code"; }
echo $response_code;
I prefer the solution with $http_response_header, because it is faster when getting a website's content.