dsxon40042 2016-03-04 15:48
浏览 61
已采纳

PHP - 如何可用,如何重定向到https?

I know how to redirect to https with PHP, but does anyone know how to redirect only if the site is requested via HTTP and HTTPS is available on the server?

  • 写回答

2条回答 默认 最新

  • doob0526 2016-03-04 16:21
    关注

    I don't know of a way to check a server's available protocols via php. Also, if there is one, you get lost when you want to check and redirect to a remote server. So in order to check wether your destination server is capable of handling https request you need to query it. Here is an example with 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'));
    

    The method checkAvailability simple tests if a curling url returns a success HTTP-Code between 200 and 399. This is not as accurate as it could be, but shall be sufficient for this use case. So if you call this method with a https url you get your desired info wether a webserver accepts https traffic

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解