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
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报