CakePHP check if user is logged in inside a view

前端 未结 12 1882
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 13:00

I have the following code:

    Auth->user())
    {
        echo $this->element(\'header\');
    }
    else
    {
        e         


        
相关标签:
12条回答
  • 2020-12-24 13:33

    Try this

    class AppController extends Controller{
        $this->user = false;
    
       public function beforeFilter(){
         $this->user = $this->Auth->user();
       }
    
       public function beforeRender(){
          $this->set('logged_user',$this->user);
       }
    }
    

    Now You can check $logged_user in the view as

    if($logged_user){
      // users logged in $logged_user have all the details
    }else{
      // not logged in
    }
    
    0 讨论(0)
  • 2020-12-24 13:34

    in cakephp 3 you can check authentication session in the view like this

    if($this->request->Session()->read('Auth.User')){
    //do when login
    }
    else{
     //do not login
    }
    
    0 讨论(0)
  • 2020-12-24 13:35
    //In the views (or layout)
    $session->check('Auth.User.id');
    
    //In controller
    $this->Auth->User('id'); 
    
    0 讨论(0)
  • 2020-12-24 13:37

    You don't need to do $this->set(compact('authUser')); only use this in View:

    if ($this->Session->read('Auth.User')){
    // do something 
    }
    
    0 讨论(0)
  • 2020-12-24 13:40

    As of CakePHP 2.x:

    <?php if (AuthComponent::user('id')): ?>
       Logged in as <?= AuthComponent::user('name') ?>
    <?php endif; ?>
    
    0 讨论(0)
  • 2020-12-24 13:43

    This works in Cakephp 3+ (juts modify: "Auth.User.username" to suit your session data)

    <?php
    
    if (is_null($this->request->session()->read('Auth.User.username'))) {
    
        echo "....logged out";
    
    } else {
    
        echo "You are Logged in As " . $this->request->session()->read('Auth.User.username'); 
    
    }
    
    ?>
    
    0 讨论(0)
提交回复
热议问题