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

发布于 2024-10-14 13:37:36 字数 639 浏览 3 评论 0原文

我正在使用 CodeIgniter 的会话库,它在服务器端非常容易访问。在客户端,会话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:"用户名";s:8:"夏天 N"; s:6:"status";s:1:"1";}fc0f1e75c097be7970b815a630bf33ef

咳咳。我想访问“username”,它当前设置为 8 个字符的字符串 Summer N。有没有一种明显的方法可以解析它我应该只使用正则表达式吗?或者更好的方法是使用更简单的数据格式创建我自己的“用户”cookie,然后让 CI 会话单独执行自己的操作?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

圈圈圆圆圈圈 2024-10-21 13:37:36

我不相信你可以。

您需要做的是使用 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');
}

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');
}
燃情 2024-10-21 13:37:36

嗯,它是一个 cookie,所以你可以在 JS 中读取 cookie 值,是的,你可以使用 javascript 解析它,但这似乎不是一个好主意。它基本上是 php 序列化 数据,但 reg exp 可以处理它。

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

你可以使用控制器并像 Thorpe 一样使用 ajax 获取用户名建议。

或者,如果您需要用户名,为什么不将其设置在响应中的 javascript 变量中:

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

看起来比解释 cookie 更直接、更可靠。而且它随时可用,因此您无需等待 ajax 调用返回即可使用。

如果您的用户未登录,请将其设置为 null 或类似的值。

额外:您真的需要用户名吗?除非你将其传递给第三方,否则你的网络服务器总是知道用户名是什么..它是会话的一部分..(或者也许我错过了你想要做的事情)

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)

夜夜流光相皎洁 2024-10-21 13:37:36

我同意之前发帖者的观点,即 ajax 请求是最佳的,并且 cookie 应该加密,但有时项目不允许这样做。就我而言,我想避免对后端的额外攻击,并且 cookie 中存储的任何内容都不是个人性质的。这是我的两种方法,都是新鲜的,所以买者自负,因为它们还没有经过严格的测试。

请注意,CI 会话 cookie 通常只是一个带有 MD5 校验和的序列化数组,以防止篡改。我扔掉了校验和并且不关心它,所以如果你关心它,你将不得不调整这个代码。我的代码也不会转换对象或浮点数,它们也会在冲突中迷失。

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

典型用法如下:

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

享受吧!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文