Welcome Guest, Not a member yet? Register   Sign In
Using Sessions for High Traffic with AJAX
#1

I was reading the CodeIgniter 3 documentation on using sessions and high traffic with AJAX, and it recommends using session_write_close().
My application has functions that write and read directly from $_SESSION, as an example below.

PHP Code:
function setSession($index$value) {
    $_SESSION[$index] = $value;
}
function 
getSession($index) {
    if (isset($_SESSION[$index]) {
        return $_SESSION[$index];
    } else {
        return FALSE;
    }

From what I understand from the documentation these two functions should always have session_start() at the beginning and session_write_close() at the end, correct?

Another issue that I found strange, CodeIgniter already has by default a session_start() function that is automatically triggered at the beginning of execution, without intervention from my code.
What would this session_start() look like if my functions are going to call it every time something is fetched from the session?
Reply
#2

I load the sessions in my BaseController like this.

PHP Code:
// Ensure that the session is started and running
if (session_status() == PHP_SESSION_NONE)
{
 
    // $this->session = \Config\Services::session();
 
    
     
// Below - add to top - use \Config\Services;
 
    $this->session Services::session();

What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

(This post was last modified: 05-19-2022, 07:26 AM by ElTomTom.)

I still use CodeIgniter version 3.

I'm basing myself on this sentence from the session documentation (Session Library — CodeIgniter 3.1.13 documentation):
Long story short - call session_write_close() once you no longer need anything to do with session variables. 

The problem is that sometimes I use session at the beginning of the code, then halfway through the code.

In this case from what I understand the best thing would be for my code to be like this, correct?

PHP Code:
function setSession($index$value) {

    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    $_SESSION[$index] = $value;

    session_write_close();
}

function 
getSession($index) {

    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    $value FALSE;

    if (isset($_SESSION[$index]) {
        $value $_SESSION[$index];
    }

    session_write_close();

Reply
#4

That should work fine for you.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB