How to create a simple logout link in the view?

You are viewing revision #3 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.

next (#4) »

  1. The Logout in the CMenu Widget
  2. The Logout Link
  3. Show Logout only to logged-in users

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:

<?php if (!Yii::app()->user->isGuest){
    <a href="<?php echo Yii::app()->createAbsoluteUrl('site/logout'); ?>">Logout</a>
}?>
What Does Not Work
<a href="<?php echo Yii::app()->request->baseUrl; ?>/site/logout">Logout</a>
  • <a href="Yii::app()->user->logout();echo Yii::app()->homeUrl; ">Logout</a>