简体   繁体   中英

How can I access CodeIgniter session cookie using Javascript?

I'm using CodeIgniter's session library , which is really easy to access on the server side. On the client side, the session cookie looks like this (I bolded the part I'm interested in):

a:7:{s:10:"session_id";s:32:"47fe66476b098ff092f2fbdddfa53ffa";s:10:"ip_address";s:9:"127.0.0.1";s:10:"user_agent";s:50:"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv";s:13:"last_activity";s:10:"1296180527";s:7:"user_id";s:3:"895";s:8: "username";s:8:"Summer N" ;s:6:"status";s:1:"1";}fc0f1e75c097be7970b815a630bf33ef

Ahem. I want to access "username", which is currently set as the 8-character string Summer N. Is there an obvious way to parse this in javascript? Should I just use a regex? Or is the better way going to be creating my own "user" cookie with a simpler data format, and just letting CI's sessions do their own thing separately?

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
});

// PHP

function 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM