How to limit number of guest page views

You are viewing revision #1 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 (#2) »

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 291 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