PHP how to ping a server without system()

2019-07-07 05:07发布

问题:

I'm trying to ping a server but my host disabled exec() and system() because of security reasons.
Are there any other options to let it work or do I have to ask my host to enable them?

The error I get:

Warning: system() has been disabled for security reasons
Warning: exec() has been disabled for security reasons

回答1:

You can do that by using the PHP socket functions

A function for pinging from the notes on the PHP website:

function ping($host, $timeout = 1) {
            /* ICMP ping packet with a pre-calculated checksum */
            $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
            $socket  = socket_create(AF_INET, SOCK_RAW, 1);
            socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
            socket_connect($socket, $host, null);

            $ts = microtime(true);
            socket_send($socket, $package, strLen($package), 0);
            if (socket_read($socket, 255))
                    $result = microtime(true) - $ts;
            else    $result = false;
            socket_close($socket);

            return $result;
    }

But chances are good that if you are not allowed to do system calls the socket functions are also disabled.



标签: php ip ping