'PHP how to ping a server without system() or exec()
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
Solution 1:[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.
Solution 2:[2]
You can use this function :
function ping($host,$port=80,$timeout=6)
{
$fsock=fsockopen($host,$port,$errno,$errstr,$timeout);
if(!$fsock)
{
return false;
}else
{
return true;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | hasan mousavi |
