从头文件查看Codeigniter会话 [英] Codeigniter Sessions Checking from a header view file

查看:60
本文介绍了从头文件查看Codeigniter会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还很年轻,刚开始使用Codeigniter,并且在会话方面遇到了一些困惑。

I am fairly new and just started to use Codeigniter, and have come across some confusion regarding sessions.

我想要实现的是,就像在常规php中一样,我想检查用户是否使用检查会话数据的标头包含文件登录。我不想在将数据传递到视图文件时在每个控制器中检查/编写该检查代码。

What I want to achieve is, like in regular php, I want to check if a user is logged in by using a header include file which checks the session data. I dont want to check/write that checking code in every controller while passing data to the view file.

有人可以告诉我如何做到这一点吗?

Can someone please show me how it can be done?

例如我不想在每个控制器中执行以下操作:

Ex. I don't want to do the following in every controller:

//Controller:
if($this->session->userdata('loggedin'){
$data['loggedin'] = $this->session->userdata('loggedin');
}
//I dont want to check the above on every function in every controller
$this->load->view('some_view_file', $data);

//some_view_file
if(isset($loggedin)){
echo "You are logged in!";
}
else
{
echo "Please log in!";
}

相反,我希望有以下内容:

Instead, I want something to like the following:

//some view file
if(isset($loggedin))
{
echo "your logged in";
}
else
{
echo "please log in";
}

此外,我如何使用本机php会话代替CI会话。任何帮助将不胜感激。

And also, how can I use native php sessions instead of CI Sessions. Any help will be much appreciated. Thanks.

推荐答案

首先,没有理由不能只写这样的东西s:

Firstly, theres no reason you can't just write something like this in your view:

<? echo ($this->session->userdata('loggedin')) ? "Logged In": "Not Logged In"; ?>

然后,您的控制器就不需要任何代码。

Then your controllers don't need any of that code.

但是,如果检查比较复杂,则可以在一些地方进行。

However if the check is more complex or something, then theres a few places you can do it.

1)在自定义控制器的构造函数中:创建一个新文件 application / core / MY_Controller.php ,并用类似以下内容的构造函数覆盖:

1) In the constructor of a custom controller: create a new file application/core/MY_Controller.php, and override the constructor with something like:

class MY_Controller extends CI_Controller 
{
    public function __construct() 
    {
        parent::__construct();
        if($this->session->userdata("loggedin")) {
            // do something
        }
    }
}

然后让所有控制器扩展MY_Controller。

then make all your controllers extend MY_Controller.

2)或在 post_controller_constructor 挂钩中。 http://codeigniter.com/user_guide/general/hooks.html (更多透明的,如果您已经拥有大量的控制器,可能会更容易)

2) Or in a post_controller_constructor hook. http://codeigniter.com/user_guide/general/hooks.html (this is more transparent, and probably easier if you have tons of controllers already)

您可以使用本机会话:
http://codeigniter.com/wiki/Native_session/

You can use native sessions with this: http://codeigniter.com/wiki/Native_session/

这篇关于从头文件查看Codeigniter会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆