I must start off with admiting that my PHP skills are very limited, however being a very experienced Perl hacker this is very similar to me.
I needed a script that checked for a normal HTTP response from another server, a status script to see if the other server(s) where behaving as they should.
The resources on-line for PHP are great and I quickly found the code needed to retrieve a remote page and read the contents. I also found some tutorials describing how to use this code. My version ended up looking like this (thanks phptoys.com for the tutorial!):
<?php
// check responsetime for a webbserver
function pingDomain($domain){
$starttime = microtime(true);
$file = fsockopen ($domain, 80, $errno, $errstr, 10);
$stoptime = microtime(true);
$status = 0;
if (!$file){
$status = -1; // Site is down
}
else{
fclose($file);
$status = ($stoptime - $starttime) * 1000;
$status = floor($status);
}
return $status;
}
?>
This code works just fine as long as the server is up, but fsockopen generates an error message when the server is down. Here is the problem: the code is intended to verify that the server is up and take action when it is not and therefore I do not want to display the error message (as I half expect it).
I’ve tried to find a way to supress this error message (that I know will occur at some point) but could find no on-line resource describing it. In lack of a proper solution I instead made a hack innovative solution. I know when the error message will show up and that it will be written to output, to avoid this I simply put the function call in an “invisible” space of HTML:
<div style="display:none;">
<?php
$status = pingDomain('www.fireflake.com');
?>
</div>
Sure, it will still show up in the code but after this code is run you will have the response time in the $status variable and the possible error message will only be visible to someone who inspects the code! If $status is -1 the server is unreachable and 0 and up is the response time.
Also, due to the fact that DNS servers usually return a “search engine” response when a domain is unknown, you are better of using IP-numbers for checking that servers are truly on-line or not (I hope they have a fixed IP!). If not you would have to read a file from the server and make sure it has the contents you expect to be sure you are on the right server and your DNS isn’t fooling you.
EDIT: Thx for adding the tip to use @ to supress error messages. Just use @fsockopen to supress the inevitable error message.
you can suppress errors from all php functions by adding “@” to the front of them. you just need to call @fsockopen to not show the error message.
how could you display the result which returned buy pingDomain funciton?
please let me know.