Installation
composer require crossjoin/browscap
For PHP 7.x (latest), 5.6 (v2.x), or 5.3 (v1.x), ensure compatibility aligns with your project.
Basic Usage
use Crossjoin\Browscap\Browscap;
$browscap = new Browscap();
$browser = $browscap->getBrowser('Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1');
// Output: Array with device/browser properties (e.g., `platform`, `device_type`, `browser_name`).
print_r($browser);
First Use Case
$ua = request()->header('User-Agent');
$browser = $browscap->getBrowser($ua);
return response()->json(['device' => $browser['device_type']]);
Middleware Integration Parse user agents globally for analytics or conditional logic:
namespace App\Http\Middleware;
use Crossjoin\Browscap\Browscap;
class DetectBrowser
{
protected $browscap;
public function __construct(Browscap $browscap)
{
$this->browscap = $browscap;
}
public function handle($request, Closure $next)
{
$request->browser = $this->browscap->getBrowser($request->header('User-Agent'));
return $next($request);
}
}
Caching Strategies Cache results for performance (e.g., Redis):
$cacheKey = 'browser_' . md5($ua);
$browser = cache()->remember($cacheKey, now()->addHours(1), function() use ($browscap, $ua) {
return $browscap->getBrowser($ua);
});
Automatic Updates
Enable auto-updates via config (config/browscap.php):
'update' => [
'enabled' => true,
'frequency' => 'daily', // or 'weekly'
],
Custom Fields: Extend the parser with additional logic:
$browser = $browscap->getBrowser($ua);
$browser['is_mobile'] = in_array($browser['device_type'], ['smartphone', 'tablet']);
Bulk Processing:
$uas = ['UA1', 'UA2', 'UA3'];
$results = array_map([$browscap, 'getBrowser'], $uas);
User-Agent Spoofing
if (empty($browser['browser_name'])) {
$browser = ['browser_name' => 'Unknown', 'platform' => 'Unknown'];
}
Memory Usage
getBrowser() sparingly or batch-process.Update Conflicts
storage/browscap lacks write permissions. Set:
chmod -R 755 storage/browscap
$browscap->getVersion(); // Check installed Browscap version.
$browscap->getLastUpdate(); // Confirm auto-update status.
if (empty($browser['browser_name'])) {
\Log::warning("Unknown UA: {$ua}");
}
Custom Data Files Override the default Browscap file path in config:
'path' => storage_path('custom/browscap.ini'),
Hooks for Post-Processing
Extend the Browscap class to add custom logic:
class CustomBrowscap extends Browscap
{
public function getBrowser($ua)
{
$browser = parent::getBrowser($ua);
$browser['custom_field'] = $this->customLogic($browser);
return $browser;
}
}
Performance Tuning
Disable unused features (e.g., parse_ua_string if only checking cached results).
How can I help you explore Laravel packages today?