mobiledetect/mobiledetectlib
Lightweight PHP library to detect mobile devices and tablets using User-Agent and HTTP headers. Provides simple checks like isMobile() and isTablet(), regularly updated with device rules, and easy to install via Composer for any PHP app.
Installation:
composer require mobiledetect/mobiledetectlib
Use version ^4.11 for Laravel (PHP 8.2+).
Basic Usage:
use Detection\MobileDetect;
$detect = new MobileDetect();
if ($detect->isMobile()) {
// Mobile-specific logic
}
First Use Case: Redirect mobile users to a mobile-optimized URL in Laravel middleware:
use Detection\MobileDetect;
public function handle($request, Closure $next)
{
$detect = new MobileDetect();
if ($detect->isMobile() && !$request->is('mobile/*')) {
return redirect()->route('mobile.home');
}
return $next($request);
}
isMobile(): Detects phones/tablets (returns bool).isTablet(): Explicit tablet detection.getUserAgent(): Access raw User-Agent string.setHttpHeaders(): Manually set headers (useful for testing).Middleware Integration:
// app/Http/Middleware/MobileDetectMiddleware.php
public function handle($request, Closure $next)
{
$detect = new MobileDetect();
$request->merge(['is_mobile' => $detect->isMobile()]);
return $next($request);
}
Access via $request->is_mobile in controllers/views.
Dynamic View Logic:
@if($request->is_mobile)
@include('mobile.partial')
@else
@include('desktop.partial')
@endif
API Feature Gating:
if ($detect->isMobile() && $detect->isTablet()) {
return response()->json(['features' => ['touch-optimized']]);
}
Caching User-Agent Parsing (for long-running processes):
$detect = new MobileDetect([
'cache' => new \Detection\Cache\Cache(
new \Psr\SimpleCache\CachePool([
'psr16' => new \Symfony\Component\Cache\Adapter\FilesystemAdapter()
])
)
]);
Custom Device Detection: Extend the library by overriding regex patterns:
$detect->setUserAgent('Custom-UA');
if ($detect->match('CustomDeviceRegex')) {
// Handle custom device
}
CloudFront/Proxy Headers:
$detect->setHttpHeaders([
'HTTP_CF_CONNECTING_IP' => $request->ip(),
'HTTP_USER_AGENT' => $request->userAgent()
]);
Service Provider Binding:
// app/Providers/AppServiceProvider.php
public function register()
{
$this->app->singleton(MobileDetect::class, function () {
return new MobileDetect(['autoInitOfHttpHeaders' => true]);
});
}
Request Macro:
// app/Providers/AppServiceProvider.php
public function boot()
{
Request::macro('isMobile', function () {
return app(MobileDetect::class)->isMobile();
});
}
Usage: $request->isMobile().
Testing:
$detect = new MobileDetect();
$detect->setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X)');
$this->assertTrue($detect->isMobile());
Missing User-Agent:
No user-agent has been set (since v4.8.01).autoInitOfHttpHeaders is true (default) or manually set:
$detect->setHttpHeaders($_SERVER);
Cache Bloat:
$cache = new \Detection\Cache\Cache(new \Psr\SimpleCache\CachePool(), 1000); // Max 1000 entries
$detect = new MobileDetect(['cache' => $cache]);
Regex Overrides:
$detect->setRegex('CustomDevice', ['iPhone', 'iPad']);
PHP 8.4 Implicit Nulls:
^4.9.0 for compatibility.Inspect Raw Data:
$detect->setUserAgent($request->userAgent());
dd($detect->getUserAgent(), $detect->getHttpHeaders());
Test User-Agents: Use the demo site to validate detection logic.
Cache Debugging:
$detect->getCache()->evictExpired(); // Manually clean expired entries
Custom Cache Backends:
Implement Psr\SimpleCache\CacheInterface and inject:
$detect = new MobileDetect([
'cache' => new \Detection\Cache\Cache(new \RedisCache())
]);
Override Detection Logic:
Extend the class and override methods like isMobile():
class CustomMobileDetect extends MobileDetect {
public function isMobile() {
return parent::isMobile() && $this->isTouchScreen();
}
}
HTTP Headers:
Use Sec-CH-UA-Mobile (Chrome 114+) for modern detection:
$detect->setHttpHeaders([
'HTTP_SEC_CH_UA_MOBILE' => '?0'
]);
maximumUserAgentLength: Default 500 (truncates longer strings).
cacheKeyFn: Customize key generation (e.g., for multi-tenant apps):
$detect = new MobileDetect([
'cacheKeyFn' => fn($key) => "tenant_{$tenantId}_{$key}"
]);
autoInitOfHttpHeaders: Set to false if using custom headers (e.g., in tests).
How can I help you explore Laravel packages today?