如何在“无法连接”时重定向到另一台本地主机Firefox无法在某个ip上与服务器建立连接


How to redirect to another localhost when "Unable to connect Firefox can't establish a connection to the server at ''some ip

我用php为我的android应用程序创建了一个webservice,在php的头中,我给出了代码

header("Location: http://123.123.123.123/Main/sub.php?details=".$rawdata);

请注意,这是一个封闭的网络ip,这个ip只能从同一个网络访问,所以当我将WIFI网络更改为另一个时,我需要将上面的代码更改为

header("Location: http://123.123.123.124/Main/sub.php?details=".$rawdata);

如果不改变它,我会得到错误信息为"Unable to connect Firefox can't establish a connection to the server at 123.123.123.123"

我想要的是,当我切换网络从A到B,而不是上面的错误页面,我希望页面被重定向到第二个代码中指定的位置。谁来帮帮我

您可以通过设置简单的检查来检查天气主机是否可访问

  $host = 'http://123.123.123.123';
    // Number of seconds to wait for a response from remote host
    $timeout = 2;
    // TCP port to connect to
    $port = 80;
    // Try and connect
    if ($sock = fsockopen($host, $port, $errNo, $errStr, $timeout)) {
        // Connected successfully
        $up = TRUE;
        fclose($sock); // Drop connection immediately for tidiness
    } else {
        // Connection failed
        $up = FALSE;
    }
   if ($up) {
      header("Location: http://123.123.123.123/Main/sub.php?details=".$rawdata);
   }
   else {
       header("Location: http://123.123.123.124/Main/sub.php?details=".$rawdata);
   }
通过此检查,您可以轻松地相应地重定向位置。您可以根据脚本执行时间更改超时时间。

可以通过$_SERVER["REMOTE_ADDR"]判断客户端的IP地址。这应该允许您根据需要执行重定向。ip2long在这种情况下非常有用,例如:

if ((ip2long($_SERVER['REMOTE_ADDR']) & 0xffffff00) == ip2long('123.123.123.0')) {
   header("Location: http://123.123.123.124/Main/sub.php?details=".$rawdata);
} else {
   header("Location: http://123.123.123.123/Main/sub.php?details=".$rawdata);
}

ip2long将点表示的IP地址转换为long。这将允许您执行位操作,使子网匹配非常直接。

当然我建议你避免硬编码任何IP范围或地址到你的代码。将它们存储在数据库或其他地方,当事情发生变化时,它们可以很容易地维护。