PHP code example of ghdj / laravel-visitor-tracker

1. Go to this page and download the library: Download ghdj/laravel-visitor-tracker library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ghdj / laravel-visitor-tracker example snippets


return [
    // Enable/disable tracking globally
    'enabled' => env('VISITOR_TRACKER_ENABLED', true),
    
    // Paths to exclude from tracking
    'exclude' => [
        'paths' => ['api/*', 'admin/*'],
        'methods' => ['OPTIONS', 'HEAD'],
        'status_codes' => [301, 302, 404, 500],
        'ips' => [],
        'user_agents' => [],
    ],
    
    // Bot tracking
    'bots' => [
        'track' => false,
        'detect' => true,
        'additional_patterns' => [], // Add custom bot patterns
    ],
    
    // Custom parser patterns
    'parser' => [
        'additional_browsers' => [], // Add custom browser patterns
        'additional_platforms' => [], // Add custom platform patterns
    ],
    
    // Geolocation (optional - uses Laravel HTTP client)
    'geolocation' => [
        'enabled' => env('VISITOR_TRACKER_GEOLOCATION', false),
        'provider' => 'ip-api', // ip-api (free), ipinfo, ipapi
    ],
    
    // GDPR compliance
    'privacy' => [
        'gdpr_safe_mode' => env('VISITOR_TRACKER_GDPR_SAFE', false),
        'anonymize_ip' => env('VISITOR_TRACKER_ANONYMIZE_IP', false),
        'respect_dnt' => true,
    ],
    
    // Data retention
    'retention' => [
        'days' => 90,
    ],
    
    // Queue for async tracking
    'queue' => [
        'enabled' => env('VISITOR_TRACKER_QUEUE', false),
    ],
];

// In routes/web.php
Route::middleware(['track-visitor'])->group(function () {
    Route::get('/', [HomeController::class, 'index']);
    // ... more routes
});

// Or globally in bootstrap/app.php (Laravel 11)
->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        \Ghdj\VisitorTracker\Middleware\TrackVisitor::class,
    ]);
})

use Ghdj\VisitorTracker\Facades\VisitorTracker;

// Get statistics
$stats = VisitorTracker::stats();

// Total visitors (unique)
$totalVisitors = $stats->totalVisitors();

// Total page views
$totalPageViews = $stats->totalPageViews();

// Currently online visitors
$onlineNow = $stats->onlineVisitors();

// Today's visitors
$todayVisitors = $stats->todayVisitors();

// Visitors in last N days
$weeklyVisitors = $stats->visitorsLastDays(7);

// Most visited pages
$topPages = $stats->mostVisitedPages(10);

// Top referrers
$topReferrers = $stats->topReferrers(10);

// Browser statistics
$browsers = $stats->browserStats();

// Platform/OS statistics
$platforms = $stats->platformStats();

// Device type statistics
$devices = $stats->deviceStats();

// Country statistics (

// Get tracker instance
$tracker = visitor();

// Get statistics
$stats = visitor()->stats()->summary();
$online = visitor_stats()->onlineVisitors();

use Ghdj\VisitorTracker\Models\Visitor;
use Ghdj\VisitorTracker\Models\Visit;

// Get all visitors
$visitors = Visitor::all();

// Get online visitors
$online = Visitor::online()->get();

// Get visitors excluding bots
$humans = Visitor::excludeBots()->get();

// Get authenticated visitors only
$authenticated = Visitor::authenticated()->get();

// Get visitors from date range
$recent = Visitor::between(now()->subWeek(), now())->get();

// Get visits for a specific path
$homeVisits = Visit::path('/')->get();

// Get visits with referrers
$referred = Visit::withReferrer()->get();

use Ghdj\VisitorTracker\Services\UserAgentParser;
use Ghdj\VisitorTracker\Services\BotDetector;

// Parse user agent
$parser = new UserAgentParser();
$result = $parser->parse($request->userAgent());
// Returns: ['browser' => 'Chrome', 'browser_version' => '120.0', 'platform' => 'Windows', ...]

// Detect bots
$detector = new BotDetector();
$isBot = $detector->isBot($request->userAgent());
$botName = $detector->getBotName($request->userAgent());
$category = $detector->getBotCategory($request->userAgent()); // search_engine, social_media, ai_bot, etc.

// Add custom browser detection
$parser = new UserAgentParser();
$parser->addBrowserPatterns([
    'MyCustomBrowser' => '/MyCustomBrowser\/([0-9.]+)/',
]);

// Add custom bot detection
$detector = new BotDetector();
$detector->addPatterns(['mycustombot', 'anotherbot']);
$detector->addBotNames(['mycustombot' => 'My Custom Bot']);

// Or via config
// config/visitor-tracker.php
'parser' => [
    'additional_browsers' => [
        'MyBrowser' => '/MyBrowser\/([0-9.]+)/',
    ],
],
'bots' => [
    'additional_patterns' => ['mycustombot'],
],

use Ghdj\VisitorTracker\Events\VisitorTracked;

// In EventServiceProvider or using Event facade
Event::listen(VisitorTracked::class, function (VisitorTracked $event) {
    $visitor = $event->visitor;
    $visit = $event->visit;
    
    // Custom logic here
    logger("New visit from {$visitor->ip} to {$visit->path}");
});

use Illuminate\Support\Facades\Schedule;

Schedule::command('visitor-tracker:prune --force')->daily();

->withMiddleware(function (Middleware $middleware) {
    $middleware->trustProxies(at: '*'); // Or a specific list of proxy IPs
})

'dashboard' => [
    'enabled' => true,
    'token' => env('VISITOR_TRACKER_TOKEN'),
    'middleware' => ['web'], // No 'auth' needed
],

'dashboard' => [
    'enabled' => true,
    'middleware' => ['web', 'auth'],
],

// In AuthServiceProvider
Gate::define('view-visitor-stats', function ($user) {
    return $user->is_admin;
});

// In config/visitor-tracker.php
'dashboard' => [
    'enabled' => true,
    'middleware' => ['web', 'auth'],
    'gate' => 'view-visitor-stats',
],

// Check if GDPR safe mode is enabled
if (VisitorTracker::isGdprSafeMode()) {
    // No personal data being collected
}
bash
php artisan vendor:publish --tag="visitor-tracker-config"
bash
php artisan migrate
bash
# Show visitor statistics
php artisan visitor-tracker:stats
php artisan visitor-tracker:stats --detailed

# Prune old data
php artisan visitor-tracker:prune
php artisan visitor-tracker:prune --days=30
php artisan visitor-tracker:prune --force