Accessing CodeIgniter Session Data using External Scripts

Support this website by purchasing prints of my photographs! Check them out here.
DEPRECATED: This post may no longer be relevant or 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:

$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']);
Tags: #php
Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript and is an O'Reilly published author.