How to create a simple logout link in the view?

You are viewing revision #4 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#3)next (#5) »

  1. The Logout in the CMenu Widget
  2. The Logout Link

Here you learn to create and set a simple ahref-link to logout the current user.

The Logout in the CMenu Widget

The starting Yii Web Application comes with the main-view located under /protected/views/layouts/main.php and the CMenu Widget in the mainmenu div:

<div id="mainmenu">
  <?php $this->widget('zii.widgets.CMenu',array(
    'items'=>array(
	array('label'=>'Home', 'url'=>array('post/index')),
	array('label'=>'About', 'url'=>array('site/page', 'view'=>'about')),
	array('label'=>'Contact', 'url'=>array('site/contact')),
	array('label'=>'Login', 
              'url'=>array('site/login'), 
              'visible'=>Yii::app()->user->isGuest),
	array('label'=>'Logout ('.Yii::app()->user->name.')', 
              'url'=>array('site/logout'), 
              'visible'=>!Yii::app()->user->isGuest)
	),
  )); ?>
</div><!-- mainmenu -->

The Logout Link

If you wanted your Logout-Link or -Button somewhere else, than in the Widget-Menu, create a link like the following:

<a href="<?php echo Yii::app()->createAbsoluteUrl('site/logout'); ?>">Logout</a>

The route goes to the actionLogout()-Method of your SiteController. Your current user will logout on clicking the link and get redirected to your projects homeUrl.

public function actionLogout() {
    Yii::app()->user->logout();
    $this->redirect(Yii::app()->homeUrl);
 }
Show Logout only to logged-in users

Just wrap an if arround your code and ask if the user is not a guest:

<?php if (!Yii::app()->user->isGuest){
    <a href="<?php echo Yii::app()->createAbsoluteUrl('site/logout'); ?>">Logout</a>
}?>