CodeIgniter-如何获取会话以检测用户是否已登录?

时间:2018-09-13 09:38:39

标签: php html codeigniter

我有一个非常简单的页面,需要登录才能查看。我有一个登录控制器,并且视图将在成功登录后重定向到主页。但是,如果用户直接访问主页链接,我想检测用户是否已登录;如果未登录,则应将用户重定向回登录页面。

我的登录控制器:

<?php  
defined('BASEPATH') OR exit('No direct script access allowed');  

class Login extends CI_Controller {  

    public function index()  
    {  
        $this->load->view('login_view');  
    }  
    public function process()  
    {  
        $user = $this->input->post('user');  
        $pass = $this->input->post('pass');  
        if ($user=='admin' && $pass=='123')   
        {  
            $this->session->set_userdata(array('user'=>$user));  
            redirect("Report");
        }  
        else{  
            $data['error'] = 'Your Account is Invalid';  
            $this->load->view('login_view', $data);  
        }  
    }  
    public function logout()  
    {  
        $this->session->unset_userdata('user');  
        redirect("Login");  
    }  
}  
?>  

和我的登录视图:

<!DOCTYPE html>  
<html>  
<head>  
    <title>Login Page</title>  
</head>  
<body>  
    <?php echo isset($error) ? $error : ''; ?>  
    <form method="post" action="<?php echo base_url('Login/process'); ?>">  
        <table cellpadding="2" cellspacing="2">  
            <tr>  
                <td><th>Username:</th></td>  
                <td><input type="text" name="user"></td>  
            </tr>  
            <tr>  
                <td><th>Password:</th></td>  
                <td><input type="password" name="pass"></td>  
            </tr>  
            <tr>  
                <td> </td>  
                <td><input type="submit" value="Login"></td>  
            </tr>  
        </table>  
    </form>  
</body>  
</html>  

虽然登录过程运行良好,但是我不确定如何从我的主页获取会话以检测用户是否已登录。我知道我应该在主控制器中添加一些验证,但是我不知道确定如何,请帮助谢谢。

主控制器:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class EstoreReport extends CI_Controller {

public function __construct() {
  parent::__construct();
  $this->load->model('ReportModel');
}

public function index()
{
   $report=new ReportModel;
   $data['data']=$report->get_report();
   $this->load->view('includes/header');
   $this->load->view('Report/list',$data);
   $this->load->view('includes/footer');
}

7 个答案:

答案 0 :(得分:2)

您可以创建一个函数并调用它以检查用户是否已登录

downloaded = getURL(urlfile, ssl.verifypeer=FALSE)

答案 1 :(得分:1)

假设自动加载了会话助手,就像在Login控制器上进行验证一样,您可以在Main / Report控制器的index方法中设置验证:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class EstoreReport extends CI_Controller {

public function __construct() {
parent::__construct();
$this->load->model('ReportModel');
}

public function index()
{
    if (!isset($this->session->userdata('user'))) {
        redirect("Login");  
    } else {
        $report=new ReportModel;
        $data['data']=$report->get_report();
        $this->load->view('includes/header');
        $this->load->view('Report/list',$data);
        $this->load->view('includes/footer');
    }
}

答案 2 :(得分:1)

您可以根据CI docs使用$this->session->has_userdata()

所以

// Write a boolean returning method
/**
* Returns if there is a user session
*
* @return bool
*/
public function isLoggedIn()
{
    return $this->session->has_userdata($some_defined_key_like_user_id);
}

...

// Then in your index controller method
/**
* Index controller method
*
* @return void
*/
public function index()
{
    $this->isLoggedIn() ? $this->load()->view('login') : redirect("Report");
}

答案 3 :(得分:0)

您可以从下面的函数调用中获得true或false,请在您的控制器中调用此函数,然后根据响应进行重定向。

$this->session->userdata( 'logged_in' );

答案 4 :(得分:0)

控制器

public function index()
{
    //redirect to dashboard
    $this->dashboard();
}
public function dashboard()
{ //session wise operating isset session-> dashboard ,else login page
    if ($this->session->userdata('userName')) {
         //if user found
        return $this->load->view('dashboard');
    } else {
        //if "no user found"
        return $this->load->view('login');
    }
}
public function login_check()
{ //functions retrives two values 1-user type 2-userId
    $data['userdata'] = $this->Mdl_login->Login_check();

    if ($data['userdata'] == false) {
        $this->load->view('login', $data);
    } else {
        redirect(base_url('index.php/dashboard'), 'refresh');
    }
}
function logout()
{ //session destroy function
    $this->session->unset_userdata('userName');
   redirect(base_url(), 'refresh');
}

型号

 function Login_check()
{
    $username = $this->input->post('UserName');
    $password = $this->input->post("PassWord");

    //check with your value 
    $this->db->where('userName', $username);
    $this->db->where('password', $password);
    $qry_getuserdata = $this->db->get('user_tbl');
    if ($qry_getuserdata->num_rows() > 0) {
        $result = $qry_getuserdata->result();
        $userid = $result[0]->userId;
        $usertype = $result[0]->userType;
        $email = $result[0]->email;
        $this->session->set_userdata('userName', $username);
        $this->session->set_userdata('userId', $userid);
        $this->session->set_userdata('userType', $usertype);
        $this->session->set_userdata('email', $email);
        return true;
    } else {
        return false;
    }
}

现在您可以在任何地方访问会话数据

if(isset($_SESSION['userName'])){ $data['userName']= $_SESSION['userName']; }

答案 5 :(得分:0)

尝试一下

    class Login extends CI_Controller {

        public function __construct() {
            parent::__construct();
            $this->load->model('loginmodel', 'login');
            $this->load->library('form_validation');
        }

        public function index() {
            $this->load->view('admin/login');
        }

        // Check for user login process
        public function user_aouth() {

            $this->form_validation->set_rules('username', 'Username', 'trim|required');
            $this->form_validation->set_rules('password', 'Password', 'trim|required');

            if ($this->form_validation->run() == FALSE) {
                $this->session->set_flashdata('error', 'Invalid Username and Password');
                redirect('login');
            } else {
                $username = $this->input->post('username');
                $password = $this->input->post('password');
                $data = array(
                    'username' => $username,
                    'password' => $password
                );
                if ($this->login->check_valid_user_details($data)) {
                    $session_data = array(
                        'username' => $username
                    );
                    $this->session->set_userdata($session_data);
//redirect to admin user dashboard
                    redirect('dashboard');
                } else {
                    $this->session->set_flashdata('error', 'Invalid Username and Password');
                    redirect('login');
                }
            }
        }

        public function logout() {
            $this->session->unset_userdata('username');
            $this->session->sess_destroy();
            redirect('login');
        }

    }

在您的登录模型中

public function check_valid_user_details($data) {
        $condition = "username=" . "'" . $data['username'] . "'" . "AND password=" . "'" . $data['password'] . "'";
        $c = $this->db->select('*')
                ->from('admin')
                ->where($condition)
                ->limit(1);
        $query = $this->db->get();

        if ($query->num_rows() == 1) {
            return $query->result();
        } else {
            return FALSE;
        }
    }

在信息中心下每个页面的顶部使用它

 if($this->session->userdata('username') == NULL){ 
     redirect('login');
} 

答案 6 :(得分:0)

只需在控制器index()中进行简单配置即可:
使用$this->session->userdata('user') == NULL检查用户是否登录

 public function index()
 {
   if($this->session->userdata('user') == NULL)
   { 
      redirect('Login');
   }
   else
   {
      $report=new ReportModel;
      $data['data']=$orders->get_report();
      $this->load->view('includes/header');
      $this->load->view('Report/list',$data);
      $this->load->view('includes/footer');
   }
}