How can I access CodeIgniter session cookie using Javascript? How can I access CodeIgniter session cookie using Javascript? codeigniter codeigniter

How can I access CodeIgniter session cookie using Javascript?


I don't believe you can.

What you need to do is use Ajax to retrieve it.

// javascript/jquery$.post(<?php echo site_url('controller/get_session');?>, function(username) {    // username is your session var});// PHPfunction get_session() {    echo $this->session->userdata('username');}


Well it is a cookie, so you could just read the cookie value in JS, and yes, you could potentially parse it with javascript but that doesn't seem like a good idea. It's basically php serialized data but a reg exp could handle that.

First thing, you really should set CodeIgniter to encrypt the session cookie, it'll be a lot safer, which kind of denies you trying to parse the cookie (a good thing)

You could use a controller and fetch the username with ajax like Thorpe suggested.

Or, if you need the username why don't you just set it in a javascript variable in your response:

<script type='text/javascript'>var ci_username = '<?php /* awsome php code that echos the username goes here */ ?>';</script>

Seems more straight forward and more reliable than interpreting the cookie. And it's readily available so you don't need to wait for an ajax call to return before it's available.

And if your user isn't logged in, set it to null or something like that.

Extra: do you really need the username anyway? Unless you pass it on to 3rd party, your web server always know what the username is.. it's part of the session.. (or maybe i'm missing what you're trying to do)


I agree with previous posters that the ajax request is optimal and that the cookie should be encrypted, but sometimes a project doesn't allow that. In my case I wanted to avoid additional hits to the back end, and nothing stored in the cookie was of a personal nature. So here are my two methods, both are freshly minted so caveat emptor as they haven't been robustly tested.

Note, the CI session cookie typically is only a serialized array with an MD5 checksum to prevent tampering. I throw out the checksum and don't bother with it so if you care about it you will have to tweak this code. My code also doesn't convert object or floats, they get lost in the fray as well.

/** * Retrieves either a single cookie or the entire set of cookies. The array * is indexed by the cookie name. * @param cookie - name of the cookie you are interested in; can be null * @return - associative array of the cookies, or a string if you asked for a specific one *  **/function cookieCutter(cookie){    var rawcookie = unescape(document.cookie.replace(/\+/g, '%20'));    var elems = rawcookie.split('=');    var cookies = {};    for(var i=0; i < elems.length; i++){        cookies[elems[i]] = elems[i+1];        i++;    }    if(null != cookie){      return(cookies[cookie]);    }    return(cookies);}/** * Given a string that represents the contents of a server-side serialized PHP object, this * method will parse it out and return the appropriate object. * @param str - the serialized string * @return love and goodness of name=value pairs as an associative array for each item in the object * **/function parseSerializedPHP(str){    switch(str[0]){        case 'a':            var retArray = {};            var matches = str.match(/a:(\d+):(\{.*\})/);            var count = parseInt(matches[1]) * 2;            var subElems = matches[2].match(/((s:\d+:"[^"]*";)|([b|i|f]:\d+))/g);            for(var i=0; i < subElems.length; i++){                key = parseSerializedPHP(subElems[i]);                retArray[key] = parseSerializedPHP(subElems[i+1]);                i++;            }            return(retArray);            break;        case 's':            return(str.split('"')[1]);            break;        case 'i':            return(parseInt(str.match(/\d+/)));            break;        case 'b':            return( parseInt(str.match(/\d+/)) ? true : false );            break;      }    return(null);}

Typical usage is like so:

ciSessionItems = parseSerializedPHP(cookieCutter('my_sess_key'));

Enjoy!