How to limit number of guest page views

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

« previous (#1)

In some cases, we have to limit the number of page views for the guests users. Yii provide an efficient method to get this.

Here is how you can do this, if your application requires this.

Open file

protected/components/Controller.php

and add the following code there in

public function beforeAction($action) {
        // allowed actions to be performed 
        $allowed=array(
            'login','register','passwordreset','updatepassword','logout'
        );
        // page views
        if(!isset(Yii::app()->session['pages'])){
            Yii::app()->session['pages']=1;
        }else{
            Yii::app()->session['pages']=Yii::app()->session['pages']+1;
        }
        $pages = Yii::app()->session['pages'];
        if(Yii::app()->user->isGuest){
            if($pages>10){
            
                if(!in_array($action->id, $allowed)){
                    $this->redirect(array('/member/login')); // redirect to login
                }
            }
        }   
        return parent::beforeAction($action);
    }
2 0
5 followers
Viewed: 9 280 times
Version: Unknown (update)
Category: How-tos
Written by: PeRoChAk
Last updated by: CeBe
Created on: Feb 28, 2014
Last updated: 10 years ago
Update Article

Revisions

View all history

Related Articles