开发者

PHP - Maintaining session when redirecting from HTTP to HTTPS?

I'm working on a simple shopping cart. When the user clicks checkout the URL changes from HTTP to HTTPS. Unfortunately the session does not appear to carry over and I get errors about $_SESSION['cart'] (where I hold the info) not existing.

I tried using mod_rewrite to redirect all HTTP to HTTPS so that the session would al开发者_Go百科l be on HTTPS:

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

This worked. However, one page has Google Maps embedded on it, and it's a HTTP URL so IE gives warnings about some elements being insecure etc.

So, I either need to know how to exclude a page with mod-rewrite (it sent me on an infinite redirect loop when I tried) or else to maintain the session between http and https. Thanks.


There's no reason to make your entire website use https, you could do something like this to only redirect necessary pages to https:

# force https for checkout pages
RewriteCond %{HTTPS} !on
RewriteCond %{SCRIPT_FILENAME} (checkout|register|login).php$
RewriteRule (.*) https://www.example.com/$1 [R,QSA,L]

# non-secure pages
RewriteCond %{HTTPS} on
RewriteCond %{SCRIPT_FILENAME} !(checkout|register|login).php$
RewriteRule (.*) http://www.example.com/$1 [R,QSA,L]

There's no reason you can't access a cookie set from http on a secure page, I do this all the time (unless you're using secure cookies, if that's the case the solution is to not use secure cookies or make sure your entire store is https).

Also, if you're redirecting from, say, http://example.com to http://www.example.com you will lose your cookies.

But to answer your question, if you want to make your entire site use https except the map page, you could do something like this:

RewriteCond %{HTTPS} !on
RewriteCond %{SCRIPT_FILENAME} !map.php
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

RewriteCond %{HTTPS} on
RewriteCond %{SCRIPT_FILENAME} map.php
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}


Lots of approaches here: Session lost when switching from HTTP to HTTPS in PHP

Just a though on handling HTTPS in links on the page - One way of handling this is to have your absolute url be a definite constant that is different depending on whether or not SSL is active.

if(!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off'){
define('ABS_URL' , 'http://www.your-domain.com'); 
}else if($_SERVER['HTTPS'] == 'on'){
define('ABS_URL' , 'https://www.your-domain.com'); 
}

You can then replace ALL instances of your absolute url in the checkout page with ABS_URL.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜