Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter – how to avoid database caching for sessions

I'm developing a website (with a shopping cart) on top of Codeigniter, and want to use the sess_use_database setting to make it more difficult for users to hack a shopping cart session.

I also want to use database caching to speed up common DB requests (such as 'get categories' as most of the DB content won't change regularly), so I have enabled this setting:

$db['development']['cache_on'] = TRUE; 
//where 'development' is my environment

As a result, I am finding that session contents aren't being refreshed, for example on this request:

$this->basket_contents = array_values($this->session->userdata('basket_contents'));

Also, I have tried this:

$this->db->cache_off();

...before the session request, but it doesn't solve the problem (I assume because it isn't a direct DB request).

My session setings are as follows:

$config['sess_cookie_name']     = 'str_session';
$config['sess_expiration']      = 7200;
$config['sess_encrypt_cookie']  = FALSE;
$config['sess_use_database']    = TRUE;
$config['sess_table_name']      = 'ci_sessions';
$config['sess_match_ip']        = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update']  = 300;

Can I prevent caching of session-related DB requests? Or prevent certain tables from being cached?

OR is there another (probably obvious) solution I've not thought of?

Thanks in advance.

like image 929
Ade Avatar asked Dec 12 '10 22:12

Ade


2 Answers

In CodeIgniter caching is an all-or-nothing solution, you can't enable it for individual tables.

There are two options I can think of:

  • don't use CI's generic caching, but use a cache library like http://philsturgeon.co.uk/code/codeigniter-cache
  • hack db_driver.php. On line 265 (CI 1.7.2) it checks if caching is enabled. Alter that line so it doesn't do it when it's a SELECT on the sessions table.
like image 161
WanWizard Avatar answered Sep 27 '22 23:09

WanWizard


In version up to 2.2.1 there could be simple solution:

in file system/libraries/Session.php

find line with string "$query = $this->CI->db->get($this->sess_table_name);"

  1. before the line put:

    // saving cache_on
    $cache_on = $this->CI->db->cache_on;
    $this->CI->db->cache_on = false;
    
  2. after the line put:

    // restoring cache_on
    $this->CI->db->cache_on = $cache_on;
    

This will prevent mysql caching for this exact session query, leaving your cache logic as it is.

Mind that this edit concerns framework system file, so if you upgrade CI to upper version - this hack will be lost.

like image 42
ishubin Avatar answered Sep 27 '22 23:09

ishubin