CodeIgniter Shopping Cart: For Separate User Sessions

CodeIgniter shopping cart functionality has an inbuilt  ‘cart’ library. A very well written documentation of the Cart Class is available in the CI documentation ofEllislab.

As described in the document link, “The Cart Class permits items to be added to a session that stays active while a user is browsing your site. These items can be retrieved and displayed in a standard “shopping cart” format, allowing the user to update the quantity or remove items from the cart.”

However, the CodeIgniter shopping cart sessions need to be separate for a guest user who is not logged in and a logged in user.

Also Read: Use Magento Canonical Meta Tag To Improve Website Ranking

More clearly we can say that, if you are a member and have signed in to an e-commerce website, your shopping cart should display only the items that you have chosen to buy, and not also list those items which were chosen by any other user sometime back, before you decided to do some shopping (whether that user had signed in or not)!

Also, any guest user, who has not signed in or any other member, should not be able to see your shopping cart items.

To handle this, you need to work with the session variables in a certain way during Login and Logout of a  user from the website.

To start with, you need to follow the steps given in the CI Documentation to build and implement  the core CodeIgniter shopping cart functionality.

Thereafter, add a few more functions using mysql, and php sessions variables.

Please take a look at the below code snippet:

1
2
3
4
5
6
function front_user_login()
{
….user login code….(starting user sessions)..
$this->get_user_cart_contents($usrid);
header("location:Homepage");
}

This is a normal user login function. As the user is logged in and session variables are set, the code invokes another function called get_user_cart_contents() with a parameter carrying the user id (which is a unique Id for each user who is a member).

Let us take a look at this function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function get_user_cart_contents($usrid)
{
//Removes any cart contents from cart session by any other user (guest or member)
$this->session->unset_userdata('cart_contents');
$this->load->database;
$this->load->library('cart');
//Loads the cart items which were stored by the particular user in database table
$sql = "SELECT * FROM ".TABLE_CART_DATA." WHERE user_id=".$usrid;
$q = $this->db->query($sql);
$res = $q->result();
foreach($res as $val)
{
//Fetches the cart field ‘options’ from database as an array
$options_arr = explode(",", $val->options);
foreach($options_arr as $arr)
{
$arr_new = explode(":", $arr);
$options[$arr_new[0]] = $arr_new[1];
}
//Inserts the newly fetched cart data for the particular user into this session as per cart class format
$data = array('id'=> $val->product_id, 'qty'=>$val->quantity, 'price'=> $val->price, 'name'=> $val->product_name, 'image'=> $val->image, 'url'=> $val->url, 'options'=>$options);
$this->cart->product_name_rules = '[:print:]';
$this->cart->insert($data);
}
$cart_data = $this->session->userdata('cart_contents');
}

The code snippet and the comments make it pretty clear that we are first removing any cart items that might be present in CodeIgniter shopping cart session before this user, and then fetching the user’s shopping cart products from a database table (if any were chosen and stored before) and inserting them in this sessions ‘cart_contents’.

After this, we can again normally use the rest of the CodeIgniter shopping cart functionality.

But to fetch user data from database, we also need to write back cart contents into the database table from a user’s session.

CodeIgniter Shopping Cart Class

You can do this while the user is logging out. Take a look at the logout function below:

1
2
3
4
5
6
7
8
function logout_action()
{
//store cart contents from a user session into the database table
$this->store_user_cart_contents();
$this->session->unset_userdata('usrid');              //usrid is checked at each page to see if user is logged in, so on logout, unset usrid
$this->session->unset_userdata('session_id');
header("location:Login_Page");
}

This is a normal logout function which unsets the session user id after a user has clicked the logout button. But just before the user id is unset, one more function is called here. The store_user_cart_contents() function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function store_user_cart_contents()
{
$this->load->database;
$userid = $this->session->userdata('usrid');
//Deletes the old cart contents of the particular user to avoid duplication of user's cart contents
$sql1 = "DELETE FROM ".TABLE_CART_DATA." WHERE user_id=".$userid;
$q1 = $this->db->query($sql1);
//Taking the slice of the cart_contents containing the cart items only. We do not need to store the ‘cart total’ or the ‘total items’.
$contents = array_slice($this->session->userdata('cart_contents'),0,count($this->session->userdata('cart_contents'))-2); //removing 'total items' and 'cart total' from cart contents array
foreach($contents as $items)
{
//Storing the cart_contents ‘options’ array field as a string.
foreach($items['options'] as $key => $value)
{
$data[] = $key.":".$value;
}
$options = implode(",",$data);
//Insert new cart contents of user into database table
$sql = "Insert into ".TABLE_CART_DATA." (user_id,row_id,product_id,quantity,price,product_name,image,url,options) VALUES(".$userid.", '".$items['rowid']."', ".$items['id'].", ".$items['qty'].", ".$items['price'].", '".$items['name']."', '".$items['image']."', '".$items['url']."', '".$options."')";
$q = $this->db->query($sql);
}
}

So just before the user logs out, his cart contents are stored in the database for the next time he logs in to buy or check his cart.

Using these functionalities we can differentiate between the Codeigniter shopping cart of different members as well as a member and a guest user. Since we are not only using the CI Cart Class and sessions but also the DB tables to store a user’s cart contents, any clash between shopping cart of different users, whether he is a member or a guest can be avoided.

Leave a comment