我有这个小脚本,可以对$hosts_to_ping数组中的IP进行ping操作.在index.html中使用JavaScript调用此PHP.
I have this little script, which should ping the IPs in the $hosts_to_ping array. This PHP is called with JavaScript in the index.html.
但是出了点问题,因为$rval始终为1(这意味着主机不可访问).但是我知道前两个主机还活着.
But something is wrong, because the $rval is always 1 (which mean the host is unreachable). But I know that the first two host are alive.
所以我打印$res变量,然后看到消息:Need to give the IP.我不明白为什么它不能将$host变量替换为函数中的实际IP地址.
So I print the $res variable, and I see the message: Need to give the IP. I don't understand why it doesn't replace the $host variable to the actual IP address in the function.
<?php function ping($host) { exec(sprintf('ping -n 4', escapeshellarg($host)), $res, $rval); print_r($res); return $rval === 0; } $hosts_to_ping = array('10.54.23.254', '10.22.23.254', '10.23.66.134'); ?> <ul> <?php foreach ($hosts_to_ping as $host): ?> <li> <?php echo $host; ?> <?php $up = ping($host); ?> (<img src="<?php echo $up ? 'on' : 'off'; ?>" alt="<?php echo $up ? 'up' : 'down'; ?>">) </li> <?php endforeach; ?> </ul>推荐答案
在这一行:
exec(sprintf('ping -n 4', escapeshellarg($host)), $res, $rval);sprintf 不会在字符串中插入escapeshellarg($host),因为您错过了%s .将该行替换为:
sprintf won't interpolate escapeshellarg($host) in the string because you missed the %s. Replace that line with:
exec(sprintf('ping -n 4 %s', escapeshellarg($host)), $res, $rval);尝试一下,看看是否可行.
Try this and see if it works.
更多推荐
PHP函数错误
发布评论