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条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大