Error in PHP function

可紊 提交于 2019-12-11 16:25:43

问题


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>

回答1:


At this line:

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

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.




回答2:


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);



来源:https://stackoverflow.com/questions/2880255/error-in-php-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!