Get Http response code from URL. Check 200 or 404 status in PHP.

What is the simplest way how to get http response code via PHP ? How can I easily check URL for 200 or 404 status ?
0
give a positive ratinggive a negative rating
24 Mar 2024 at 02:59 PM
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.
0
give a positive ratinggive a negative rating
05 Apr 2024 at 07:26 PM
Tim
Share on FacebookShare on TwitterShare on LinkedInSend email
x
x
2024 AnswerTabsTermsContact us