文章的浏览量redis存储,关闭浏览器算做一次

作者:谢高升 发布:2018-03-20 浏览:2992次

需求;打开网站直到关闭浏览器浏览量+1;

使用yii2.0的框架,用redis来存储点击量;使用cookie来区分;

<?php
/**
 * Created by PhpStorm.
 * User: xiaoxie
 * Date: 2017/6/17
 * Time: 23:41
 */

namespace frontend\controllers\base;


use yii\web\Controller;
use Yii;

class BaseController extends Controller
{
    public function beforeAction($action){
        if(!parent::beforeAction($action)){
            return false;
        }
        $times = mktime(23,59,59) - mktime(date('H'),date('i'),date('s'));
        $redis = Yii::$app->redis;
         $redis->auth('admin');
        $num = $redis->get('xiaoxietotal');
        //第一次打开的时候是没有cookie的
        if (isset($_COOKIE['advanced-frontend'])){
            $cookie = $_COOKIE['advanced-frontend'];
            $key = $redis->get($cookie);
            if (!$key){
                $redis->set($cookie,1);
                //30分钟过期
                $redis->expire($cookie,30*60);
                if ($num)
                {
                  //  $redis->incr('xiaoxietotal');
                }else{
                    $redis->set('xiaoxietotal',1);
                }
                $todayTotal = $redis->get('xiaoxietoday');
                if ($todayTotal)
                {
                   // $redis->incr('xiaoxietoday');
                }else{
                    $redis->set('xiaoxietoday',1);
                    //当天的浏览量设置0点过期
                    $redis->expire('xiaoxietoday',$times);
                }
            }
        }else{
			//echo 123;
			if ($num)
			{
				$redis->incr('xiaoxietotal');
			}else{
				$redis->set('xiaoxietotal',1);
			}
			$todayTotal = $redis->get('xiaoxietoday');
			if ($todayTotal)
			{
				$redis->incr('xiaoxietoday');
			}else{
				$redis->set('xiaoxietoday',1);
				//当天的浏览量设置0点过期
				$redis->expire('xiaoxietoday',$times);
			}
		}


        return true;
    }
}

image.png