PHP函数错误 [英] Error in PHP function

查看:91
本文介绍了PHP函数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个小脚本,可以对$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函数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆