Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Browscap Php Laravel Package

browscap/browscap-php

browscap-php is a PHP library for detecting browser, platform, and device details from User-Agent strings using the Browscap database. It provides easy updates, caching, and a simple API for accurate capability detection in web apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require browscap/browscap-php
    

    Ensure your composer.json includes the package under require.

  2. First Use Case: Detecting User Agents

    use BrowscapPHP\Browscap;
    
    $browscap = new Browscap();
    $browscap->setBrowserPath(__DIR__ . '/path/to/browscap.ini'); // Download from [Browscap](https://browscap.org/)
    $device = $browscap->getBrowser('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
    
    // Output device properties
    print_r($device->getBrowser());
    
  3. Where to Look First

    • Official Documentation: BrowscapPHP GitHub (if available) or Browscap.org.
    • Sample browscap.ini: Download the latest .ini file from Browscap and place it in your project (e.g., storage/browscap.ini).
    • Laravel Cache: Store the parsed .ini file in cache for performance (see Implementation Patterns).

Implementation Patterns

1. Caching the Browscap Data

Avoid parsing the .ini file on every request by caching the parsed data:

use Illuminate\Support\Facades\Cache;

$browscap = new Browscap();
$cacheKey = 'browscap_data';

if (!Cache::has($cacheKey)) {
    $browscap->setBrowserPath(storage_path('browscap.ini'));
    Cache::put($cacheKey, $browscap->getParsedBrowsers(), now()->addDays(7));
} else {
    $browscap->setParsedBrowsers(Cache::get($cacheKey));
}

$device = $browscap->getBrowser($_SERVER['HTTP_USER_AGENT']);

2. Middleware for Automatic Detection

Create a middleware to attach browser/device info to the request:

// app/Http/Middleware/DetectBrowser.php
public function handle($request, Closure $next) {
    $browscap = new Browscap();
    $browscap->setParsedBrowsers(Cache::get('browscap_data'));
    $device = $browscap->getBrowser($request->userAgent());

    $request->merge([
        'browser' => $device->getBrowser(),
        'platform' => $device->getPlatform(),
        'isMobile' => $device->isMobileDevice(),
    ]);

    return $next($request);
}

Register the middleware in app/Http/Kernel.php:

protected $middleware = [
    // ...
    \App\Http\Middleware\DetectBrowser::class,
];

3. Dynamic Updates via API

Fetch updates from Browscap’s API (if available) and regenerate the cache:

// Example: Trigger via Artisan command
use Illuminate\Console\Command;

class UpdateBrowscap extends Command
{
    protected $signature = 'browscap:update';
    protected $description = 'Update Browscap data from API';

    public function handle() {
        $iniContent = file_get_contents('https://example.com/browscap.ini'); // Hypothetical API
        file_put_contents(storage_path('browscap.ini'), $iniContent);
        Cache::forget('browscap_data'); // Invalidate cache
        $this->info('Browscap updated!');
    }
}

4. Integration with Laravel Views

Pass browser data to Blade templates:

// In a controller
return view('dashboard', [
    'browser' => $request->browser,
    'isMobile' => $request->isMobile,
]);
@if($isMobile)
    <div class="mobile-alert">Mobile user detected!</div>
@endif

5. Custom Logic Based on Device

Use detected properties to tailor responses:

if ($device->isMobileDevice()) {
    return redirect()->route('mobile.home');
}

if ($device->getBrowser() === 'IE') {
    abort(403, 'Internet Explorer is not supported.');
}

Gotchas and Tips

Pitfalls

  1. Outdated .ini File

    • Browscap data becomes stale quickly. Schedule regular updates (e.g., weekly via cron or Laravel tasks).
    • Fix: Use the UpdateBrowscap command (above) or integrate with Browscap’s API if available.
  2. Memory Usage

    • Parsing large .ini files can spike memory. Cache aggressively and avoid parsing on every request.
    • Fix: Cache the parsed data (as shown in Implementation Patterns).
  3. User-Agent Spoofing

    • Users can fake their HTTP_USER_AGENT. Validate critical actions (e.g., payments) with additional checks.
    • Fix: Combine with IP-based detection or CAPTCHAs for sensitive actions.
  4. Case Sensitivity

    • User-agent strings are case-insensitive, but the .ini file may have quirks. Test edge cases.
    • Fix: Normalize the input string before passing to getBrowser():
      $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
      
  5. Laravel Service Provider Conflicts

    • If using multiple packages that modify $_SERVER or $_REQUEST, ensure HTTP_USER_AGENT isn’t altered before detection.
    • Fix: Detect early in the request lifecycle (e.g., in middleware).

Debugging Tips

  1. Verify .ini File Check if the file is readable and valid:

    if (!$browscap->getBrowserPath()) {
        throw new \RuntimeException('Browscap file not set or unreadable.');
    }
    
  2. Log Undetected User Agents Log cases where no match is found to improve coverage:

    $device = $browscap->getBrowser($userAgent);
    if (!$device) {
        \Log::warning("Unrecognized user agent: {$userAgent}");
    }
    
  3. Test with Known Strings Use hardcoded user-agent strings to verify detection:

    $testAgents = [
        'Chrome', 'Safari', 'Firefox', 'Edge', 'iPhone', 'Android'
    ];
    foreach ($testAgents as $agent) {
        $device = $browscap->getBrowser("Mozilla/5.0 ($agent)");
        dump($device->getBrowser());
    }
    

Extension Points

  1. Custom Properties Extend the Browscap class to add domain-specific logic:

    class CustomBrowscap extends Browscap {
        public function isSupported() {
            $browser = $this->getBrowser();
            return !in_array($browser, ['IE', 'EdgeLegacy']);
        }
    }
    
  2. Database Storage Store frequently accessed devices in a database table for ultra-fast lookups:

    // Cache to DB after first detection
    if (!$device->getId()) {
        DB::table('detected_devices')->insert([
            'user_agent' => $userAgent,
            'browser' => $device->getBrowser(),
            'created_at' => now(),
        ]);
    }
    
  3. Webhook Updates Integrate with Browscap’s webhook service (if available) to auto-update when new data is released.

  4. Fallback Logic Provide fallback behavior for unsupported browsers:

    $device = $browscap->getBrowser($userAgent);
    if (!$device) {
        return redirect()->route('unsupported-browser');
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views