美文网首页
thinkphp6 前台统计用户访问记录

thinkphp6 前台统计用户访问记录

作者: charmingcheng | 来源:发表于2023-09-25 16:57 被阅读0次

只需要在前台路由加一个中间件即可:
前台路由route.php文件:

<?php

use think\facade\Route;

Route::group('/', function() {
    Route::get('/', 'Index/index');
    Route::get('product', 'Product/index');
    Route::get('news', 'News/index');
    ...
})->middleware([\app\index\middleware\AccessCount::class]);

中间件:

<?php
declare (strict_types = 1);

namespace app\index\middleware;

class AccessCount
{
    /**
     * @param $request
     * @param \Closure $next
     * @return mixed
     */
     public function handle($request, \Closure $next)
    {
        $ip = '121.228.129.28'; // 访客ip
        $url = $request->domain().$request->url(); // 访问页面

        if (array_key_exists('HTTP_ORIGIN', $_SERVER)) {
            $origin = $_SERVER['HTTP_ORIGIN']; // 访问来源
        } else if (array_key_exists('HTTP_REFERER', $_SERVER)) {
            $origin = $_SERVER['HTTP_REFERER']; // 访问来源
        } else {
            $origin = $_SERVER['REMOTE_ADDR']; // 访问来源
        }

        $ipContent  = curlRequest("https://qifu-api.baidubce.com/ip/geo/v1/district?ip={$ip}");
        $contents = json_decode($ipContent, true);

        $country = '';
        $province = '';
        $city = '';
        $district = '';
        $areacode = '';
        $adcode = '';
        $asnumber = '';

        if (isset($contents['code']) && $contents['code'] == 'Success') {
            $country = $contents['data']['country'];
            $province = $contents['data']['prov'];
            $city = $contents['data']['city'];
            $district = $contents['data']['district'];
            $areacode = $contents['data']['areacode'];
            $adcode = $contents['data']['adcode'];
            $asnumber = $contents['data']['asnumber'];
        }

        $data = [
            'ip' => $ip,
            'url' => $url,
            'origin' => $origin,
            'country' => $country,
            'province' => $province,
            'city' => $city,
            'district' => $district,
            'areacode' => $areacode,
            'adcode' => $adcode,
            'asnumber' => $asnumber,
        ];

        \app\common\model\AccessCount::create($data);

        return $next($request);
    }

百度ascode区域划分下载地址:
https://lbsyun.baidu.com/faq/api?title=webapi/download

image.png
表格转为json,查询对应的城市和地区填入数据库

laravel 同理

相关文章

网友评论

      本文标题:thinkphp6 前台统计用户访问记录

      本文链接:https://www.haomeiwen.com/subject/uzkcbdtx.html