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.
Installation
composer require browscap/browscap-php
Ensure your composer.json includes the package under require.
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());
Where to Look First
browscap.ini: Download the latest .ini file from Browscap and place it in your project (e.g., storage/browscap.ini)..ini file in cache for performance (see Implementation Patterns).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']);
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,
];
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!');
}
}
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
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.');
}
Outdated .ini File
UpdateBrowscap command (above) or integrate with Browscap’s API if available.Memory Usage
.ini files can spike memory. Cache aggressively and avoid parsing on every request.User-Agent Spoofing
HTTP_USER_AGENT. Validate critical actions (e.g., payments) with additional checks.Case Sensitivity
.ini file may have quirks. Test edge cases.getBrowser():
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
Laravel Service Provider Conflicts
$_SERVER or $_REQUEST, ensure HTTP_USER_AGENT isn’t altered before detection.Verify .ini File
Check if the file is readable and valid:
if (!$browscap->getBrowserPath()) {
throw new \RuntimeException('Browscap file not set or unreadable.');
}
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}");
}
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());
}
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']);
}
}
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(),
]);
}
Webhook Updates Integrate with Browscap’s webhook service (if available) to auto-update when new data is released.
Fallback Logic Provide fallback behavior for unsupported browsers:
$device = $browscap->getBrowser($userAgent);
if (!$device) {
return redirect()->route('unsupported-browser');
}
How can I help you explore Laravel packages today?