Question

i'm currently checking if a server(in this case 192.168.1.135) is online with this php code:

<?php 
$fp = fsockopen("192.168.1.135", 443, $errno, $errstr, 0.4); //(line 47)
if (!$fp) {
  echo "OFFLINE";
}
else{
 echo "ONLINE";
}
?>

I have this code on my own server 192.168.1.130 using XAMPP (on LAN ofcourse)

So, if this server is offline the output will be:

Warning: fsockopen(): in C:\xampp\htdocs\index.php on line 47
OFFLINE

it should just be "OFFLINE". How to show just OFFLINE without the warning?

I think XAMPP will send me the warning when the server is down. but how should I do to not show the warning? I don't find a setting for this in XAMPP, anyone know?

if no, how should i do the line 47 correct even when the server is down(offline)?

When the server is online, this will work perfecly.

Was it helpful?

Solution

Use the silence operator @ to suppress the warning:

$fp = @fsockopen("192.168.1.135", 443, $errno, $errstr, 0.4); //(line 47)

Side note: As you see, the @ operator suppressed the warning as you requested. But be careful. A message like for example 'No route to host' will being also suppressed. (Mostly if your network connection isn't available) So you cannot be sure, that the server is offline. You should additionally output $errmsg if fsockopen() fails to see the reason.

OTHER TIPS

Try this script

$fp = fsockopen("192.168.1.135", 443, $errno, $errstr, 0.4);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: 192.168.1.135\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top