How to create a simple logout link in the view?

You are viewing revision #5 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#4)

  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>
}?>
0 2
1 follower
Viewed: 48 489 times
Version: Unknown (update)
Category: How-tos
Written by: mi.sarah
Last updated by: CeBe
Created on: Feb 28, 2014
Last updated: 10 years ago
Update Article

Revisions

View all history

Related Articles