2010-05-21 79 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