2010-05-21 80 views
0

我有这个小脚本,它应该ping $hosts_to_ping阵列中的IP。这个PHP在index.html中使用JavaScript调用。PHP函数中的错误

但是有什么不对,因为$rval总是1(这意味着主机无法访问)。但我知道前两个主机还活着。

因此,我打印$res变量,我看到消息:Need to give the 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> 

回答

1

在这一行:

exec(sprintf('ping -n 4', escapeshellarg($host)), $res, $rval); 

sprintf不会在字符串中插值escapeshellarg($host),因为你错过了%S。将该行替换为:

exec(sprintf('ping -n 4 %s', escapeshellarg($host)), $res, $rval); 

试试看看它是否有效。

+0

是的..谢谢你! – Holian 2010-05-21 08:01:01

+0

不客气:-) – 2010-05-21 08:12:59

1

这是因为你没有替换你的sprintf中的任何东西。它大概应该是这样的,使其工作:exec(sprintf('ping -n 4 %s', escapeshellarg($host)), $res, $rval);

+0

对,那个作品 – Thariama 2010-05-21 07:37:27

+0

是的。谢谢! – Holian 2010-05-21 08:01:18