【问题标题】:php ping test and redirectphp ping 测试和重定向
【发布时间】:2013-03-15 18:35:37
【问题描述】:

我正在尝试让一个基本的 php ping 脚本正常工作,该脚本将 ping 我的网站 ip,如果它响应会将用户重定向到我的网站,但如果没有,它将把用户重定向到其他地方。我在下面附上了我到目前为止所拥有的内容,但目前它似乎没有在 ping 站点,因为它直接到 http://othersite.com,如下例所示。感谢您提供的任何帮助。

<?php

function ping($host)
{
    exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($host)), $res, $rval);
    return $rval === 0;
}
// random host ip example
$host = '8.8.8.8';
$online = ping($host);

// if site is online, send them to the site.
if( $online ) {
       header('Location: mysite.com');
} 
// otherwise, lets go elsewhere to an online site
else {
        header('Location: http://othersite.com/');
}

?>

【问题讨论】:

  • 你知道不同的输出吗?从 Linux 机器 ping 时?和Windows机器?如果是这样,则捕获您的输出,然后对关键短语采取行动,以便您的脚本可以识别成功或失败
  • 我没想到它是一个正在 ping 的 linux vps 我会根据这个修改脚本谢谢 :)

标签: php redirect ip ping host


【解决方案1】:

注意:您的代码似乎在 Linux 上运行良好,但在 Windows 上却不行。进一步检查,我注意到 Windows 没有为 ping 提供 -c 选项,这会导致它返回与预期不同的值,并且您的 ping 失败

exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($host)), $res, $rval);
    return $rval === 0;

这似乎假设成功时返回值将从exec 变为0?但根据PHP Manual 会是

The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function. To get the output of the executed command, be sure to set and use the output parameter.

您与返回值的比较似乎是问题所在。 $rval 包含什么值?

【讨论】:

  • 感谢您的回复,我会看看您的建议,并尝试根据这些建议使其发挥作用。我是使用 php 的新手,但我认为 $rval 应该根据主机是否在线返回 0 或 1 我使用了此 stackoverflow.com/questions/2880255/…> 中的一些代码写下来。再次感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 2013-02-13
  • 2019-04-22
  • 2011-06-05
  • 2011-01-29
  • 2013-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多