PHP 函数错误
我有这个小脚本,它应该 ping $hosts_to_ping
数组中的 IP。该 PHP 在 index.html 中通过 JavaScript 调用。
但有些地方出了问题,因为 $rval
始终为 1(这意味着主机无法访问)。但我知道前两位宿主还活着。
因此,我打印 $res
变量,然后看到消息:需要提供 IP
。我不明白为什么它不将 $host
变量替换为函数中的实际 IP 地址。
<?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>
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.
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.
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这一行:
sprintf 不会插入
escapeshellarg($host )
在字符串中,因为您错过了 %s。将该行替换为:尝试一下,看看它是否有效。
At this line:
sprintf won't interpolate
escapeshellarg($host)
in the string because you missed the %s. Replace that line with:Try this and see if it works.
那是因为你没有替换 sprintf 中的任何内容。它可能应该看起来像这样才能工作: exec(sprintf('ping -n 4 %s', escapeshellarg($host)), $res, $rval);
That's because you don't replace anything in your sprintf. It probably should look like this to make it work :
exec(sprintf('ping -n 4 %s', escapeshellarg($host)), $res, $rval);