简体   繁体   中英

PHP - Ping exec on Linux hangs script

I have a simple PHP script setup to check the status of my servers. It uses a standard ping command, run via exec().

  • On Windows, the script works fine both when a server is online and when down.
  • On Linux, the script works when the server is online, but hangs when the server is down. Timeout seems to have no effect on the latter.

Pinging with the same command via console works fine and times out correctly.


What's the cause, and how would this be fixed?

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  $exec_string = 'ping -n 1 -i 255 -w 2 ' . $host;
} else {
  $exec_string = 'ping -n -c 1 -t 255 -w 2 ' . $host;
}
exec($exec_string, $output, $return);

I would avoid pinging directly using an exec() . I use this script, found here , you can also setup port and timeout:

function ping($host, $port = 80, $timeout = 6) {
    $fsock = fsockopen($host, $port, $errno, $errstr, $timeout);
    if (!$fsock) {
        return false;
    } else {
        return true;
    }
}

$host = 'www.example.com';

if(ping($host)) {
    echo "HOST UP";
} else {
    echo "HOST DOWN";
}

I'm unsure why, but switching from suPHP to fastCGI (both with suEXEC enabled) seemed to resolve the issue and the ping properly times out as expected.

If anyone has an explanation for this, I would love to know, in either comment or answer format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM