Getting the header response code

This is the part of the PHP script that I am compiling. Basically, the domain ($ domain1) is defined in the form and another message is displayed based on the response code from the server. However, I have problems with his work. A 3 digit response code is all that interests me.

Here is what I still have:

function get_http_response_code($domain1) { $headers = get_headers($domain1); return substr($headers[0], 9, 3); foreach ($get_http_response_code as $gethead) { if ($gethead == 200) { echo "OKAY!"; } else { echo "Nokay!"; } } } 
+5
source share
4 answers
 $domain1 = 'http://google.com'; function get_http_response_code($domain1) { $headers = get_headers($domain1); return substr($headers[0], 9, 3); } $get_http_response_code = get_http_response_code($domain1); if ( $get_http_response_code == 200 ) { echo "OKAY!"; } else { echo "Nokay!"; } 
+14
source

If you have PHP 5.4.0+, you can use the http_response_code () function. Example:

 var_dump(http_response_code()); // int(200) 
+6
source

Here is my solution for people who need to send email when the server exits:

 $url = 'http://www.example.com'; while(true) { $strHeader = get_headers($url)[0]; $statusCode = substr($strHeader, 9, 3 ); if($statusCode != 200 ) { echo 'Server down.'; // Send email } else { echo 'oK'; } sleep(30); } 
0
source

You directly returned, so that the function will not fulfill the further foreach condition that you wrote. Its always better to support two functions.

 function get_http_response_code($domain1) { $headers = get_headers($domain1); return substr($headers[0], 9, 3); //**Here you should not return** foreach ($get_http_response_code as $gethead) { if ($gethead == 200) { echo "OKAY!"; } else { echo "Nokay!"; } } } 
0
source

Source: https://habr.com/ru/post/898135/


All Articles