Lưu trữ thông tin người dùng truy cập vào website
Chúng ta thường nghe thấy google ,facebook thu thập thông tin người dùng vậy các công ty thu thập thông tin như nào .Dưới đây mình sẽ hướng dẫn các bạn cách lưu thông tin người dùng 1 cách đơn giản khi người dùng truy cập vào web .
Trong nội dung hướng dẫn dưới đây hệ thống mình sử dụng :
- Laravel 9
- Mongodb Cloud
1 Tạo project laravel
Chúng ta chạy command sau để tạo 1 project laravel :
composer create-project laravel/laravel saveuserdata
Để laravel có thể sử dụng mongodb làm cơ sở dữ liệu chúng ta sử dụng packages : jenssegers/mongodb bằng command sau :
composer require jenssegers/mongodb
Tiếp theo chúng ta cần lấy thông tin người dùng như trình duyệt , hay hệ điều hành .... chúng ta dùng packages :jenssegers/agent bằng command sau :
composer require jenssegers/agent
Tiếp theo chúng ta liên kết mongodb config ở file config/database.php
// cloud serve hienlashare.info
'mongodbcloud' => [
'driver' => 'mongodb',
'dsn' => 'mongodb+srv://anhhien:@cluster0.35jfbaq.mongodb.net/?retryWrites=true&w=majority',
'database' => 'lashare',
],
Tạo model Saveuseraccess với command sau :
php artisan make:model Saveuseraccess
Trong file Saveuseraccess chúng ta code như sau :
namespace App\Models;
use App\Traits\UseAutoIncrementID;
use Illuminate\Database\Eloquent\Factories\HasFactory;
//use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\Model;
class Saveuseraccess extends Model
{
use HasFactory;
use UseAutoIncrementID;
protected $connection='mongodbcloud';
protected $table='saveuseraccess';
protected $primaryKey='id';
protected $fillable=['ip','user_id','path_info','domain','thietbi','device','platform','browser','referer','useragent'];
}
Lưu ý : ở đây mình dùng mongodb nên ko cần dùng migration
Tiếp theo chúng ta tạo middleware để bắt thông tin người dùng truy cập
Chạy command sau để tạo Middleware
php artisan make:middleware Saveuseraccess
Ở đây mình code như sau :
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Jenssegers\Agent\Agent;
class Saveuseraccess
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
$input['ip']=$request->ip();
if(Auth::id())
{
$input['user_id']=Auth::id();
}
$input['path_info'] = $request->getPathInfo();
$input['domain'] = env('APP_NAME');
$input['thietbi'] = $this->thietbi();
$agent = new Agent();
$input['device'] = $agent->device(); //Get the device name, if mobile. (iPhone, Nexus, AsusTablet, ...)
$input['platform'] = $agent->platform(); //Hệ điều hành như IOS,windows hay IOS (Ubuntu, Windows, OS X, ...)
$input['browser'] = $agent->browser(); //Get the browser name. (Chrome, IE, Safari, Firefox, ...)
$input['useragent'] = $agent->getUserAgent();
if($request->header('referer'))
{
$input['referer'] = parse_url($request->header('referer'))['host'];
}
$data_user_access = Cache::remember('middleware.'.$input['ip'].$input['path_info'],600,function () use($input)
{
\App\Jobs\SaveUserAccess::dispatch($input)->delay(Carbon::now()->addSeconds(10));
return 1;
});
return $next($request);
}
public function thietbi()
{
/*
1 là mobile ,2 là table,3 là may tinh
*/
$agent = new Agent();
if($agent->isMobile())
{
return 1;
}elseif ($agent->isTablet())
{
return 2;
}else
{
return 3;
}
}
}
Thêm middleware vào app/Http/Kernel.php
'saveuseraccess'=>Saveuseraccess::class,
Sau đó ở router nào cần lưu lại thông tin người dùng chúng ta thêm middlewave vào thôi :
Tiếp theo ở đây chúng ta tạo job :
php artisan make:job SaveUserAccess
Code như sau :
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
class SaveUserAccess implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
protected $input;
public function __construct($input)
{
$this->input = $input;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
\App\Models\Saveuseraccess::create($this->input);
}
}
1 bạn nhắn tin hỏi mình vậy lưu data như này thì càng ngày càng phình to có cách gì giảm lượng data đi không .Vậy là mình code thêm 1 job nữa :
php artisan make:job DeleteUserAccess
namespace App\Jobs;
use App\Models\Saveuseraccess;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
class DeleteUserAccess implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Saveuseraccess::chunkById(100,function ($useraccess){
foreach ($useraccess as $key=>$item)
{
// xóa dữ liệu quá 6 tháng trước thường thì dữ liệu truy cập quá 6 tháng không còn ý nghĩa mấy
//if($item->created_at < Carbon::now()->subMonths(6))
if($item->created_at < Carbon::now()->subMonths(6))
{
Saveuseraccess::where('id',$item->id)->delete();
}
}
});
}
}
Để job DeleteUserAccess chạy auto thì chúng ta vào app/Console/Kernel.php thêm dòng sau :
namespace App\Console;
use App\Console\Commands\DeleteUserAccessOld;
use App\Jobs\DeleteUserAccess;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->job(DeleteUserAccess::dispatch())->dailyAt('1:00');
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
Để chạy schedule này thì chúng ta chạy lệnh
php artisan schedule:run
kiểm tra xem có schudele chưa với lệnh
php artisan schedule:list
Vậy là oke rồi đó giờ chúng ta chạy lệnh :
php artisan serve
Và truy cập vào đường link sau : http://127.0.0.1:8000/ để xem thành quả