How to create a simple logout link in the view?

  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(
	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'=>'Logout ('.Yii::app()->user->name.')', 
  )); ?>
</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() {
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: 40 133 times
Version: 1.1
Category: How-tos
Written by: mi.sarah
Last updated by: CeBe
Created on: Feb 28, 2014
Last updated: 7 years ago
Update Article


View all history

Related Articles