简体   繁体   English

如何使用 Javascript 访问 CodeIgniter 会话 cookie?

[英]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.我正在使用CodeIgniter 的会话库,它在服务器端非常容易访问。 On the client side, the session cookie looks like this (I bolded the part I'm interested in):在客户端,会话 cookie 如下所示(我将我感兴趣的部分加粗):

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 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?我想访问“用户名”,它当前设置为 8 个字符的字符串 Summer N。有没有明显的方法可以在 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?或者更好的方法是使用更简单的数据格式创建我自己的“用户”cookie,并让 CI 的会话单独做自己的事情?

I don't believe you can.我不相信你能。

What you need to do is use Ajax to retrieve it.您需要做的是使用 Ajax 来检索它。

// 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.嗯,它是一个 cookie,所以你可以在 JS 中读取 cookie 值,是的,你可以用 javascript 解析它,但这似乎不是一个好主意。 It's basically php serialized data but a reg exp could handle that.它基本上是 php序列化数据,但 reg exp 可以处理。

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)首先,你真的应该设置 CodeIgniter 来加密会话 cookie,它会更安全,这会拒绝你尝试解析 cookie(一件好事)

You could use a controller and fetch the username with ajax like Thorpe suggested.您可以使用控制器并像索普建议的那样使用 ajax 获取用户名。

Or, if you need the username why don't you just set it in a javascript variable in your response:或者,如果您需要用户名,为什么不在响应中将其设置在 javascript 变量中:

<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.似乎比解释 cookie 更直接、更可靠。 And it's readily available so you don't need to wait for an ajax call to return before it's available.而且它随时可用,因此您无需等待 ajax 调用在它可用之前返回。

And if your user isn't logged in, set it to null or something like that.如果您的用户未登录,请将其设置为 null 或类似的内容。

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)除非您将其传递给第 3 方,否则您的网络服务器始终知道用户名是什么.. 这是会话的一部分..(或者我可能错过了您想要做的事情)

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.我同意以前的海报,ajax 请求是最佳的,cookie 应该被加密,但有时项目不允许这样做。 In my case I wanted to avoid additional hits to the back end, and nothing stored in the cookie was of a personal nature.在我的情况下,我想避免对后端的额外点击,并且 cookie 中存储的任何内容都不是个人性质的。 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.请注意,CI 会话 cookie 通常只是一个带有 MD5 校验和的序列化数组,以防止篡改。 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!享受!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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