session lost between http and https

Today I came across strange problem. Let me explain you exact problem and solution for that.

Problem:

I have e-commerce site developed. After product added to shopping cart when user trying to checkout I am redirecting user from Shopping cart to Account page (if user already logged in) or Login Page (if user not logged in) on checkout. To make transaction more secure, Transition from shopping cart to Account page or Login Page is HTTP (Non-Secure) to HTTPS (Secure). Whenever I switch from HTTP to HTTPS, My stored shopping cart items which are stored in $_SESSION variable get lost.

Solution

After much hair pooling to trace and fix this issue I have found below solution:

When you switch between the HTTP and HTTPS services on the same server, your HTTP session ID is not being passed to the HTTPS session. Here we need to pass session_id which is created by HTTP to HTTPS page. so HTTPS resume similar session on server rather then creating new session for HTTPS request. Below is the code to explain it via example:

Consider you are redirecting  http://www.example.com/page1.php to  https://www.example.com/page2.php

page1.php script:

<?php
session_start();
$sess_id = session_id();
$_SESSION['someVar'] = “Var Value”;
echo “<a href=’https://www.example.com/page2.php?sess_id=’”.$sess_id.”>Page2</a>”;
?>

page2.php script:

<?php
if(isset($_GET['sess_id']) && $_GET['sess_id']!=”")
{
session_id($_GET['sess_id']);
}
session_start();

Hope above given solution help others as well.

Post comments if you have any question.

Happy Coding. :)

Advertisement

One response to this post.

  1. Moreover, a new problem arise if you have a different subdomain for secure area, say http://www.example.com and http://secure.example.com, in fact in this case you must check that the cookie works for both url, setting by session_set_cookie_params the domain to “.example.com”.

    And this problem became more complex if you have a SSL served by ISP alias. Several Internet Service Providers offers a shared certificate, thus, as example for hosted domain mysite and yoursite you have this kind of situation:

    http://www.mysite.com
    https://mysitecom.ispsecureserver.com

    http://www.yoursite.com
    https://yoursitecom.ispsecureserver.com

    I didn’t find a way to share session data switching from http://www.mysite.com to https://mysitecom.ispsecureserver.com :-(

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.