1. 程式人生 > >文章的瀏覽量redis儲存,關閉瀏覽器算做一次

文章的瀏覽量redis儲存,關閉瀏覽器算做一次

需求;開啟網站直到關閉瀏覽器瀏覽量+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