Accessing CodeIgniter Session Data using External Scripts

DEPRECATED: This post has been marked as deprecated and may no longer contain industry best-practices.

For a project we're working on, we have the need to access CodeIgniter session data outside of our CI installation, more specifically for a WordPress installation. CodeIgniter, as most developers should already know, stores it's session data in a database and uses a cookie to refer to the data, as opposed to storing this data inside of the PHP default $_SESSION superglobal.

The CodeIgniter cookie stored on the local computer isn't just a random hash representing the session stored on the server, as it is with PHP's $_SESSION. It is actually a serialized object representing the hash, along with the users IP address and useragent, which provides a second level of security as CodeIgniter will see if this cookie really does belong to the user who has it. The data is also hashed and a signature is provided with the cookie which prevents forgery.

So, to access this data, we'll need to get the cookie from the user, remove slashes if our server has magic_quotes enabled, unserialize the data, run a SQL query to grab the data using the cookie hash we found, then unserialize the data returned from the database. Easy, huh?

Here is the code. You'll need to add some extra security measures to make sure the cookie doesn't contain SQL injection, along with checking the cookie user agent data against the data provided by the browser, but this is the quick and dirty version:

<?php
require_once("config.php");
$cisess_cookie = $_COOKIE['ci_session'];
$cisess_cookie = stripslashes($cisess_cookie);
$cisess_cookie = unserialize($cisess_cookie);
$cisess_session_id = $cisess_cookie['session_id'];

$cisess_connect = mysql_connect(MYSQL_HOSTNAME, MYSQL_USERNAME, MYSQL_PASSWORD);
if (!$cisess_connect) {
 die("<div class="error">" . mysql_error() . "</div>");
}
$cisess_query = "SELECT user_data FROM ci_sessions WHERE session_id = '$cisess_session_id' LIMIT 1";

mysql_select_db(MYSQL_DATABASE, $cisess_connect);
$cisess_result = mysql_query($cisess_query, $cisess_connect);
if (!$cisess_result) {
 die("Invalid Query");
}
$cisess_row = mysql_fetch_assoc($cisess_result);
$cisess_data = unserialize($cisess_row['user_data']);
print_r($cisess_data);
Tags: #php
Thomas Hunter II Avatar

Thomas is the author of Advanced Microservices and is a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.