开发者

Programmatically determine whether the connection is taking place over HTTP or over HTTPS?

I'd like to redirect users of my site from http://mysite to https://mysite.

开发者_开发知识库

How can I do that programmatically in PHP?


You can check if SSL is used using if(!empty($_SERVER['HTTPS'])).

If you are using the standard port, testing for $_SERVER['SERVER_PORT'] == 443 will also work, but of course checking if HTTPS is used is better than testing if the port is the default SSL port.


However, the redirect should not be done via PHP but via .htaccess (if you are using Apache):

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}


If $_SERVER['HTTPS'] is set to on, the page is loaded over https. However, you should mark your cookies as secure, which you can do with one of the parameters of setcookie. If the cookies are not secure, they may be transmitted over unencrypted http, and can potentially be stolen, even if the user is redirected immediately.

http://php.net/manual/en/function.setcookie.php

For the actual redirect, I'd use a .htaccess rewrite, rather than PHP. Create a .htaccess file with the following content.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} !=on
RewriteCond ^(.*)$ https://www.example.com/$1 [R=301,L]


Use $_SERVER['HTTPS'] to determine.


If it's https, then the variable $_SERVER['HTTPS'] will be set to nonzero:

if (isset($_SERVER['HTTPS'])) {
    # it's https
} else {
    # it's not https
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜