简体   繁体   English

检查会话用户是管理员还是简单用户

[英]Check if session users is admin or simple

i want to make if clause for button. 我想为按钮制作if子句。 If admin is logged in it will shown otherwise not. 如果管理员已登录,则不会显示。

if($this->Session->User['role'] == 'admin') {
    echo
    '<li> <a href="/VAG/dashboard"><ul class="pull-right">Admin skiltis</ul></a></li>';
}

I can't get that role from session and compare if it admin or not.. 我无法从会话中获得该角色,并且无法比较该角色是否为管理员。

Using $_SESSION['Auth']['User'] directly is a bad practice, as depending how the AuthComponent is configured, it may not be available. 直接使用$_SESSION['Auth']['User']是一种不好的做法,因为根据AuthComponent的配置方式,它可能不可用。

You should better pass the authenticated user from the controller to the views and then only check his properties: 您最好将经过身份验证的用户从控制器传递到视图,然后仅检查其属性:

AppController: AppController:

$authenticated_user = $this->Auth->user();

if(isset($authenticated_user))
{
    $this->set(compact('authenticated_user'));
}

Views: 观看次数:

if(isset($authenticated_user) && $authenticated_user['role'] == 'admin'){
    ...
}

By the way you should also use the HtmlHelper in your views to generate links instead of printing <a> tags manually with hardcoded urls to benefit from many Cake features. 顺便说一句,您还应该在视图中使用HtmlHelper来生成链接,而不是使用硬编码的URL手动打印<a>标签,以从Cake的许多功能中受益。

Try to make a little debug on your code. 尝试对您的代码进行一些调试。

First check if your session was started. 首先检查您的会话是否已开始。 You can do this by executing the command "session_status()" if the result is "PHP_SESSION_NONE" your session isnt started. 如果结果为“ PHP_SESSION_NONE”,则说明未启动会话,您可以通过执行命令“ session_status()”来执行此操作。 You can fix it by putting a "session_start()" before any print was made by your page. 您可以通过在页面进行任何打印之前放置“ session_start()”来解决此问题。

If value of print_r($_SESSION); 如果值为print_r($_SESSION); is something like, 是这样的

Array ( [Config] => Array ( [userAgent] => 4df452d8263aa05ef9324f37499322b0 [time] => 1401090120 [countdown] => 10 ) [Message] => Array ( ) [Auth] => Array ( [User] => Array ( [id] => 8 [username] => aaaaa [email] => aaa@gmail.com [role] => admin [created] => 2014-05-26 02:43:20 [modified] => 2014-05-26 02:43:20 [status] => 1 ) ) )

Thae try this code, I think it will work, 试试这个代码,我认为它会起作用,

if($_SESSION['Auth']['User']['role'] == 'admin') {
echo
'<li> <a href="/VAG/dashboard"><ul class="pull-right">Admin skiltis</ul></a></li>';
}

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

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