How to save and extract session data in codeigniter

How to save and extract session data in codeigniter

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Session Extraction Logic in CodeIgniter: A Common Pitfall

When moving session data from a controller to a model in CodeIgniter, developers often stumble over how session_start() and the CI Session library interact. The specific issue here involves extracting user activity data after validation but failing to persist it correctly because of redundant initialization and scope confusion.

In the provided VerifyLogin controller, the line session_start(); is executed inside the index() method. This is unnecessary and potentially problematic in a CodeIgniter application. The framework's Session library ($this->session) handles initialization automatically upon instantiation. Calling session_start() manually can conflict with CI's internal session tracking, leading to empty sessions or data loss when accessed later via $this->session->userdata().

The core logic flow attempts to validate credentials, then populate a session array with user details like username, IP address, and user agent before inserting this into the user_activity table. However, the extraction mechanism in the model relies on checking if 'logged_in' exists in the session data immediately after the controller sets it.

The Controller: Setting the Session Data

The validation logic in the check_database callback is sound regarding form handling. Once a user logs in successfully ($result && $captcha_code == $vercode), the code constructs a $sess_array. This array pulls the username from the database query result and supplements it with metadata like $this->user_activity->get_client_ip().

The critical line here is:

$this->session->set_userdata('logged_in', $sess_array);

This stores the entire login context into a single session key named logged_in. This is a common pattern, but it requires strict adherence to how that data is retrieved later. The variable $sess_array contains keys like 'username', 'user_agent', and 'ip_address'.

The Model: Retrieving and Inserting

The User_activity model attempts to retrieve this data in the activity() function using:

if($this->session->userdata('logged_in')) {
    $session_data = $this->session->userdata('logged_in');
    // ... insertion logic
}

Technically, this should work if the session persists between the controller call and the model call. However, there are two subtle issues in the provided code snippets that often cause failures for new developers:

  1. Redundant session_start(): As mentioned, removing the manual session_start() call prevents potential conflicts with CodeIgniter's native session driver.
  2. Variable Scope and Method Placement: In the model snippet provided, the get_client_ip() function is defined inside the activity() method. While PHP allows functions inside methods (creating a local scope), this makes the code harder to read and debug. It is best practice to define get_client_ip as a public method within the class so it can be reused elsewhere if needed.

Debugging the "Missing Username" Issue

The user reports that only the username data is saved or extracted, implying other fields might be missing or the whole block fails silently. If the code inserts only the username, check the $data array construction in the model. The line:

'username' => $session_data['username'],

will fail with a fatal error if $session_data does not contain the 'username' key, unless PHP's loose typing suppresses it or the code is catching an exception elsewhere. However, based on the logic, the most likely cause of "partial" data extraction is actually that the session data isn't being populated at all due to the session_start() conflict mentioned earlier.

If the session is not initialized correctly by CI, $this->session->userdata('logged_in') returns false or an empty array, causing the if block to skip entirely. To debug this, ensure you remove the manual session_start() call from the controller and verify that the session configuration in application/config/config.php is set to use the standard driver ('native').

Best Practice for Activity Logging

To avoid these pitfalls, decouple the IP address retrieval logic. Instead of defining a helper function inside the model method, extract it to a standalone helper or keep it as a public class method. This ensures consistent handling of headers like HTTP_X_FORWARDED_FOR.

Furthermore, consider storing the session ID explicitly if your database schema allows it. The code sets 'session_id' => "", which might be intentional for privacy, but ensuring the mapping between the database record and the actual active session can help with auditing without relying solely on server-side logs.

If you find yourself needing more robust session handling or a switch to Laravel for a larger project, tools like those offered by LaravelCompany provide excellent documentation on managing state, which can serve as a reference for how modern PHP frameworks handle these data persistence challenges differently than the procedural approach seen here.

Finally, always verify that the user_activity model is loaded correctly in the constructor. The code uses $this->load->model('user', '', TRUE) and similar calls. Ensure that no syntax errors exist in the loaded files, as a silent failure to load the model would result in undefined property notices when trying to call $this->session or $this->db.

Our network