What is browscap
browscap provides a database which can be used to find browser info if we have user agent.
//sample code for browscap 6.0.0
//sample user agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36
$cacheDir = APPLICATION_PATH . '__cache/';
$fileCache = new \League\Flysystem\Local\LocalFilesystemAdapter($cacheDir);
$filesystem = new \League\Flysystem\Filesystem($fileCache);
$cache = new \MatthiasMullie\Scrapbook\Psr16\SimpleCache(
new \MatthiasMullie\Scrapbook\Adapters\Flysystem($filesystem)
);
$logger = new \Monolog\Logger('name');
$bc = new \BrowscapPHP\Browscap($cache, $logger);
$browser = $bc->getBrowser($userAgent);
How to find cache directory
Need two steps to set up cache directory. Use --cache flag to specify cache directory. For the following set up, cache directory is /var/src/__cache
- vendor/bin/browscap-php browscap:fetch
- vendor/bin/browscap-php browscap:convert --cache /var/src/__cache
If see the error below, do two steps above again and make sure $cacheDir is the same as what specify in step 2.
there is no active cache available, please use the BrowscapUpdater and run the update command
Slove BrowscapPHP\Exception: there is no active cache available, please use the BrowscapUpdater and run the update
$cacheDir = APP_ROOT . '/composer/__cache';
$fileCache = new \League\Flysystem\Local\LocalFilesystemAdapter($cacheDir);
$filesystem = new \League\Flysystem\Filesystem($fileCache);
$cache = new \MatthiasMullie\Scrapbook\Psr16\SimpleCache(
new \MatthiasMullie\Scrapbook\Adapters\Flysystem($filesystem)
);
$logger = new \Monolog\Logger('name');
//run these two lines once and the problem is gone
// $bc = new \BrowscapPHP\BrowscapUpdater($cache, $logger);
//$bc->update(\BrowscapPHP\Helper\IniLoaderInterface::PHP_INI_FULL);
$bc = new \BrowscapPHP\Browscap($cache, $logger);