Yii 1.1: How to create a simple logout link in the view?

1 follower

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>

Be the first person to leave a comment

Please to leave your comment.

Write new article