简体   繁体   English

如果会话已过期,Codeigniter将重定向到登录页面

[英]Codeigniter redirect to login page if session already expires

I am new to codeigniter framework and I don't really get how does the built-in session works. 我是codeigniter框架的新手,我不知道内置会话是如何工作的。 What I want is that when the session expires the user will be redirected to login page. 我想要的是,当会话到期时,用户将被重定向到登录页面。 I checked the answers in google and other stackoverflow questions and tried every code in their but it does not work. 我检查了谷歌和其他stackoverflow问题的答案,并尝试了他们的每个代码,但它不起作用。 In the native php session I only need to specify that if the session expires in the given time then redirect but when I applied it in codeigniter it does not work. 在本机php会话中,我只需要指定如果会话在给定时间内到期然后重定向,但是当我在codeigniter中应用它时它不起作用。 I don't know also how to retrieve the session expiration value in config to compare it to the current time accumulated by the user during his/her logged session. 我还不知道如何在config中检索会话到期值,以将其与用户在其记录的会话期间累积的当前时间进行比较。 Please help.... 请帮忙....

This is in function in controller 这在控制器中起作用

public function check_session()
{
    $logged_in = $this->session->userdata('logged_in');

    if(!$logged_in)
    {
        $this->logout();
    }
}

And this is the ajax: 这是ajax:

setInterval(function(){
$.ajax({
    type: 'POST',
    url: "<?php echo site_url('tms/check_session');?>",
    success: function(data){
        console.log(data);
    }
});
},300);

First, create a core Controller under application/core . 首先,在application/core下创建一个核心Controller。 You can call it MY_Controller.php 你可以称之为MY_Controller.php

Here is an example for MY_Controller.php: 以下是MY_Controller.php的示例:

class User_Controller extends CI_Controller {

    public function __construct()
    {

        parent::__construct();

        if ($this->session->userdata['logged'] == TRUE)
        {
            //do something
        }
        else
        {
            redirect('login'); //if session is not there, redirect to login page
        }   

    }
}

Create your Controller Classes like below: 创建您的控制器类,如下所示:

class Someclass extends User_Controller

Also you should pass a value which called "logged" in your session array. 您还应该在会话数组中传递一个名为“logged”的值。 Eg: 例如:

$session = array('id' => $id, 'logged' => TRUE);
$this->session->set_userdata($session);

Now, if session ends, system will redirect user to login page. 现在,如果会话结束,系统会将用户重定向到登录页面。 If you want to make this session control thing via JavaScript, you should write some code for it. 如果你想通过JavaScript创建这个会话控件,你应该为它编写一些代码。 By the way, I'm not suggesting this. 顺便说一句,我不是在暗示这一点。 You don't need to increase your system's workload. 您无需增加系统的工作量。 With my code, if a session ends when user want to visit another page, system will kick him out. 使用我的代码,如果会话在用户想要访问另一个页面时结束,系统会将他踢出去。

public function check_session()
{


    if(!$this->session->userdata['logged'])
    {
        redirect('someurl');
    }
}

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

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