【问题标题】:Show message if header location redirect fails [duplicate]如果标头位置重定向失败,则显示消息[重复]
【发布时间】:2013-05-04 00:30:37
【问题描述】:

我需要重定向到一个未知地址。如果地址不可用,我想向用户显示一条消息。怎么做?

<?php
header("Location: http://www.example.com/"); 
exit;
?>

【问题讨论】:

  • 定义“不可用”
  • 首先使用file_get_contents 测试网站。如果您的网站无法连接,则显示错误。
  • 啊 ping,但网络服务器仍可能关闭。
  • @mightyuhu 最佳解决方案,同时检查标题

标签: php redirect


【解决方案1】:

最直接的方法是只检索页面:

if (file_get_contents('http://www.example.com/') !== false) {
  header("Location: http://www.example.com/"); 
  exit;
}

http://php.net/manual/en/function.file-get-contents.php

但是,这只会告诉您该页面上是否有可用的东西。它不会告诉你,例如,you got a 404 error page instead

为此(并且为了节省下载整个页面的内存成本),您可以只使用get_headers() 作为 URL:

$url = "http://www.example.com/";
$headers = get_headers($url);
if (strpos($headers[0],'200 OK') !== false) { // or something like that
  header("Location: ".$url); 
  exit;
}

【讨论】:

  • OP 需要对页面本身进行额外检查。在任何情况下,控制都会从那里失去。
  • file_get_contents 下载整个页面,为了可用性/内存,这有点多。
  • get_headers() 在这里可能就足够了。
  • @Jack 注意到了,正在编辑。
  • get_headers() 是否忽略了正文内容,也就是说,是否节省了双方的带宽?
【解决方案2】:

你可以使用 curl 来做到这一点

      $ch = curl_init(); 
      curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); 
      $output = curl_exec($ch); 
      if(curl_errno($ch)==6)
        echo "page not found";
     else
      header("Location: http://www.example.com/");      

       curl_close($ch);  

【讨论】:

    【解决方案3】:

    您可以检查 url 是否存在然后重定向:

    $url = 'http://www.asdasdasdasd.cs';
    //$url = 'http://www.google.com';
    
    if(@file_get_contents($url))
    {
        header("Location: $url"); 
    }
    else
    {
        echo '404 - not found';
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      相关资源
      最近更新 更多