gpt4 book ai didi

session - Codeigniter 用户登录检查

转载 作者:行者123 更新时间:2023-12-01 09:37:10 29 4
gpt4 key购买 nike

我是 Code Igniter 的新手,目前正在构建自己的用户系统。我正在登录过程中,并且我已经实现了检查用户当前是否登录的检查。

然后,如果他们已经登录,我想在我的标题中显示指向“注销”的链接,如果他们当前未登录,则显示“登录”的链接。

我的索引 Controller 中有一个工作函数如下,$loginstatus 变量被发送到我的页面标题 View :

function check_session()
{
//Check session status

$session = $this->session->userdata('login_state');

$default = "Log In";

if ($session == 1)
{
$url = site_url('index.php/users/logout');
$status = "Log Out";



}
else
{
$url = site_url('index.php/users/login');
$status = $default;
}

$loginstatus = array(
"url" => $url,
"status" => $status
);

return $loginstatus;
}

因为它目前仅在索引 Controller 中,所以不会为其他页面的标题 View 生成 $loginstatus,这是我的问题。

我应该把这个函数放在哪里,以便它总是在我的标题之前加载?我尝试创建一个带有“通用”类的库,然后自动加载它,但我最终遇到了很多问题。

提前致谢。

最佳答案

如果您使用 2.0 以下的 CI 版本,则在 application/libraries/MY_Controller.php 中创建新类,否则在 application/core/MY_Controller.php 中,您的所有应用程序 Controller 都应从它扩展。在 __construct 方法中的此类中,您将检查登录状态并将其发送到 View 。

class MY_Controller extends CI_Controller{    public function __construct()    {        parent::__construct();        //Get the status which is array        $login_status = $this->check_session();        //Send it to the views, it will be available everywhere        //The "load" refers to the CI_Loader library and vars is the method from that library.        //This means that $login_status which you previously set will be available in your views as $loginstatus since the array key below is called loginstatus.        $this->load->vars(array('loginstatus' => $login_status));    }    protected function check_session()    {        //Here goes your function    }}

还要确保您的应用程序 Controller 从此类扩展

//application/controllers/index.phpclass Index extends MY_Controller{    public function __construct()    {        parent::__construct();    }}

在您看来,您可以这样做:

这可能是因为 CI_Loader vars() 方法正在执行 extract到传递给它的参数。

关于session - Codeigniter 用户登录检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5614201/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com