CodeIgniter框架中session无效

框架自带session无效

背景:前端是vue, 后端是CI 3.1.10,一直无法保存登录信息

1. 配置问题

config.php 检查配置文件,不知道什么时候,配置值’ci_session’,被敲进一个空格,变成 ’ ci_session’, 所以每刷新页面就自动新增一个session_id

$config['sess_driver'] = 'files'; // 多种驱动:files 是文件驱动,搭配sess_save_path
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = FCPATH . 'public/sess_save_path'; // 必须选择文件保存位置
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

2. 跨域问题

因为vue的使用,所以导致跨域

    /**
     * Checks allowed domains, and adds appropriate headers for HTTP access control (CORS)
     *
     * @access protected
     * @return void
     */
    protected function _check_cors()
    {
        $this->config->load('rest'); // 配置文件

        // Convert the config items into strings
        $allowed_headers = implode(' ,', $this->config->item('allowed_cors_headers'));
        $allowed_methods = implode(' ,', $this->config->item('allowed_cors_methods'));

        header("Access-Control-Allow-Credentials: true");
        header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

        // If we want to allow any domain to access the API
        if ($this->config->item('allow_any_cors_domain') === TRUE) {
            header('Access-Control-Allow-Origin: *');
            header('Access-Control-Allow-Headers: ' . $allowed_headers);
            header('Access-Control-Allow-Methods: ' . $allowed_methods);
        } else {
            // We're going to allow only certain domains access
            // Store the HTTP Origin header
            $origin = $this->input->server('HTTP_ORIGIN');
            if ($origin === NULL) {
                $origin = '';
            }

            // If the origin domain is in the allowed_cors_origins list, then add the Access Control headers
            if (in_array($origin, $this->config->item('allowed_cors_origins'))) {
                header('Access-Control-Allow-Origin: ' . $origin);
                header('Access-Control-Allow-Headers: ' . $allowed_headers);
                header('Access-Control-Allow-Methods: ' . $allowed_methods);
            }
        }

        // If the request HTTP method is 'OPTIONS', kill the response and send it to the client
        if ($this->input->method() === 'options') {
            exit;
        }
    }

// 可配置话 路由 rest.php

$config['allowed_cors_headers'] = [
    'Origin',
    'X-Requested-With',
    'Content-Type',
    'Accept',
    'Access-Control-Request-Method',
    'user_token'
];
$config['allowed_cors_methods'] = [
    'GET',
    'POST',
    'OPTIONS',
    'PUT',
    'PATCH',
    'DELETE'
];
$config['allow_any_cors_domain'] = FALSE; // 是否允许所有域名跨域
// 允许跨域
$config['allowed_cors_origins'] = [
        'http://admin.xxx.com',
    ];

3. ajax请求处理

处理完上面后,ajax的请求,依旧无法获取到session保存的信息

$.ajax({
            type: 'GET',
            url: 'http://admin.xxx.com/Admin/login?username=xx&password=xx',
            headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},
            data:{},
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            ......

最后附上使用的基本方法

1. $this->load->library('session'); // 引入session文件,也可以在autoload中,自动加载
2. $this->session->userdata('key'); // 获取某个session值,相当于 $_SESSION['key']:$this->session->userdata() === $_SESSION
3. $this->session->set_userdata('key', 'value'); // 设置某个session值
4. $this->session->unset_userdata('key');  // 删除某个session值
5. $this->session->session_id; // 获取session_id

你可能感兴趣的:(笔记)