views:

73

answers:

2

Hi,

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 all 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.

+1  A: 

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}
Rob
+1  A: 

Lots of approaches here: http://stackoverflow.com/questions/441496/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.

DeaconDesperado
I believe you misordered the tests on `$_SERVER['HTTPS']`. Try: `if( (!isset($_SERVER['HTTPS'])) || ($_SERVER['HTTPS'] == 'off') ) {` instead.
MattBianco
Good eye. Corrected. Thanks.
DeaconDesperado