【问题标题】:PHP - How to redirect to https if available?PHP - 如果可用,如何重定向到 https?
【发布时间】:2016-06-18 10:26:16
【问题描述】:

我知道如何使用 PHP 重定向到 https,但有谁知道只有在通过 HTTP 请求站点并且服务器上可以使用 HTTPS 时如何重定向?

【问题讨论】:

  • 如果 https 可用,为什么要通过 http 服务请求?您可以轻松添加(每个安装)重写规则,将所有 http 请求重定向到 https。
  • 嗨。也许使用 get_headers (php.net/manual/en/function.get-headers.php)。可以测试一下httpS,如果不好就去http

标签: php http redirect ssl https


【解决方案1】:

请看这个..

<?php
if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
    // Enter 'https' URL here...(Eg: https://google.com)
} else {
    // Enter 'http' URL here... (Eg: http://google.com)
}
?>

【讨论】:

    【解决方案2】:

    我不知道如何通过 php 检查服务器的可用协议。此外,如果有的话,当您想要检查并重定向到远程服务器时,您会迷路。因此,为了检查您的目标服务器是否能够处理 https 请求,您需要对其进行查询。这是一个使用 php-curl 的示例:

    <?php
    /**
     * Check wether a destination is reachable.
     * 
     * @param string $uri uri to check
     * 
     * @return bool
     */
    function checkAvailability($uri) {
        $handle = curl_init($uri);
        curl_setopt_array($handle, [
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_USERAGENT       => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
            ]);
        $r = curl_exec($handle);
        $responseCode = (int)curl_getinfo($handle, CURLINFO_HTTP_CODE);
        curl_close($handle);
        return $responseCode > 199 && $responseCode < 400;
    }
    
    //we test by checking the webpages of two of my local newspapers, l-iz.de will succeed, lvz.de will not
    var_dump(checkAvailability('https://www.l-iz.de'));
    var_dump(checkAvailability('https://lvz.de'));
    

    方法 checkAvailability 简单测试 curl url 是否返回 200 到 399 之间的成功 HTTP 代码。这可能不够准确,但对于这个用例来说应该足够了。因此,如果您使用 https url 调用此方法,您将获得所需的信息,无论网络服务器是否接受 https 流量

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 2017-09-15
      • 2012-02-26
      • 2017-05-25
      • 1970-01-01
      • 2011-07-06
      • 2011-08-12
      相关资源
      最近更新 更多