[英]Check for active session before loading complete navigation in codeigniter 3
I have a welcome controller with index function: 我有一个带有索引功能的欢迎控制器:
public function index()
{
$this->load->view('templates\header');
$this->load->view('welcome_message');
$this->load->view('templates\footer');
}
Header view code goes like following: 标头视图代码如下所示:
<header>
<div class="navbar navbar-default navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="<?php echo base_url() ?>">
Test App
</a>
</div>
</div>
</div>
</header>
It works perfectly fine so far. 到目前为止,它的工作情况还不错。 I also want to add following code in my navigation bar (with in header tags) as a menu items but only if the user session is active.
我还想将以下代码添加到导航栏中(带有标题标签)作为菜单项,但前提是用户会话处于活动状态。 So if a user is logged in than only he/she should be able to see the menu item else the user should only see a navbar with brand name "Test App".
因此,如果用户已登录,则仅他/她应该能够看到菜单项,否则该用户只能看到品牌名称为“ Test App”的导航栏。
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="<?php echo base_url('welcome') ?>"><i class="fa fa-tachometer"></i> Dashboard</a>
</li>
<li>
<a href="<?php echo base_url('admin/logout') ?>"><i class="fa fa-sign-out"></i> Logout
</a>
</li>
</ul>
</div>
I also have a helper which check and return true or false if the user is logged in or not and i am using it inside the controller. 我还有一个帮助程序,如果用户未登录,则检查并返回true或false,并且我正在控制器内部使用它。 I am not comfortable using that inside the view because than i have to echo the menu items and adjust a lot of double/single quotes to make that work.
我不习惯在视图中使用它,因为我必须回显菜单项并调整很多双/单引号以使它起作用。 Is there a neat way to do this ?
有没有一个整洁的方式做到这一点?
Code for login helper: 登录帮助程序代码:
function is_logged_in() {
$CI =& get_instance();
$user = $CI->session->userdata('username');
if ( !isset($user) )
{
return false;
}
else
{
return true;
}
}
you can choose what to display according to the user session from controller. 您可以根据控制器上的用户会话选择要显示的内容。
For example: 例如:
if($this->session->userdata('username')<>NULL){
$data['logged_in'] = 1;
}else{
$data['logged_in'] = 0;
}
$this->load->view('templates\header',$data);
In view: 在视图中:
if($logged_in==1){
//header with logged in options
}else{
//header with normal options.
}
Why don't you use session_status()
? 为什么不使用
session_status()
?
On its documentation one of the users posted in comments universal function for checking if session is started: 在其文档中,其中一位张贴在注释通用功能中的用户用于检查会话是否已开始:
<?php
/**
* @return bool
*/
function is_session_started()
{
if ( php_sapi_name() !== 'cli' ) {
if ( version_compare(phpversion(), '5.4.0', '>=') ) {
return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
} else {
return session_id() === '' ? FALSE : TRUE;
}
}
return FALSE;
}
// Example
if ( is_session_started() === FALSE ) session_start();
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.