browscap-php

repository·7.8.x·Indexed 19 days ago

https://github.com/browscap/browscap-php

A userland replacement for PHP's native get_browser() function that provides updated browser capability detection using Browser Capabilities Project data. It includes a Browscap class for browser identification and a CLI tool for fetching, converting, and updating browscap.ini data into a PHP cache format.

Tokens
3.5K
Snippets
13
Records
14
Agent score
66%

What's inside browscap-php

  1. Set up the browscap cache (Recommended)

    7.8.x

    Before using the library, you must download the browscap.ini file and convert it into a cache. There are two recommended workflows:

    Option A: Two-step process (Manual control)

    Download the file locally, then convert it. This is useful if you want to keep the .ini file locally. If the cache is corrupted, you only need to rerun convert.

    vendor/bin/browscap-php browscap:fetch
    vendor/bin/browscap-php browscap:convert

    Option B: One-step process (Automatic update)

    Download and convert in one command. This checks if the remote file has changed. If the cache is corrupted, you must clean the cache and restart the process.

    vendor/bin/browscap-php browscap:update

    Note: It is recommended to run these commands via a separate cron job to keep your cache updated.

  2. Configure a proxy for BrowscapUpdater

    7.8.x

    If your environment requires a proxy to reach browscap.org, you can inject a custom Guzzle client into the BrowscapUpdater.

    $proxyConfig = [
        'proxy' => [
            'http'  => 'tcp://localhost:8125',
            'https' => 'tcp://localhost:8124',
        ],
    ];
    $client = new \GuzzleHttp\Client($proxyConfig);
    $bcu = new BrowscapUpdater();
    $bcu->setClient($client);
  3. Initialize and use the Browscap class

    7.8.x

    To identify a browser, instantiate \BrowscapPHP\Browscap. This class requires a PSR-16 compatible cache and a PSR-3 compatible logger. You can then call getBrowser() to identify the current user agent or pass a specific string to getBrowser($userAgent) to parse a custom string.

    $cache = new \MatthiasMullie\Scrapbook\Psr16\SimpleCache($doctrineFileCache); // Must implement PSR-16
    $logger = new \Monolog\Logger('name'); // Must implement PSR-3
    
    $browscap = new \BrowscapPHP\Browscap($cache, $logger);
    
    // Identify current user agent from $_SERVER
    $info = $browscap->getBrowser();
    
    // Identify a specific user agent
    $info = $browscap->getBrowser($the_user_agent);
  4. Use the full browscap.ini file

    7.8.x

    By default, the library uses the standard version of the browser capabilities file. To use the full version, use the BrowscapUpdater class and specify the PHP_INI_FULL constant.

    $bc = new \BrowscapPHP\BrowscapUpdater();
    $bc->update(\BrowscapPHP\Helper\IniLoaderInterface::PHP_INI_FULL);
  5. Reference: CLI commands

    7.8.x

    The browscap-php CLI tool is used for managing the cache and parsing user agents. Note that CLI commands currently only support file-based caches. If you encounter rate limits from browscap.org, an Exception will be thrown.

    ### check-update
    Check if a new version of `browscap.ini` is available.
    `vendor/bin/browscap-php browscap:check-update [--cache <path>]
    
    ### fetch
    Download the `.ini` file from browscap.org.
    `vendor/bin/browscap-php browscap:fetch [--cache <path>] [--remote-file <type>] [--file <path>]
    - --remote-file options: `PHP_BrowscapINI` (default), `Lite_PHP_BrowscapINI`, `Full_PHP_BrowscapINI`
    
    ### convert
    Convert a local `.ini` file into a cache.
    `vendor/bin/browscap-php browscap:convert [--file <path>] [--cache <path>]
    
    ### update
    Download and convert in one step (no local file stored).
    `vendor/bin/browscap-php browscap:update [--remote-file <type>] [--cache <path>]
    - --remote-file options: `PHP_BrowscapINI` (default), `Lite_PHP_BrowscapINI`, `Full_PHP_BrowscapINI`
    
    ### parse
    Parse a user agent and output to console.
    `vendor/bin/browscap-php browscap:parse --user-agent <ua> [--cache <path>]
  6. Reference the browscap.php CLI commands

    7.8.x

    The following commands are available via the bin/browscap.php entrypoint:

    convert: Converts the browscap data.
    update: Updates the browscap data.
    parser: Runs the parser.
    fetch: Fetches the browscap data.
    check-update: Checks for updates.
  7. BrowscapPHP Exception error codes

    7.8.x

    The BrowscapPHP\Exception class defines several constant error codes used to identify specific failure scenarios during Browscap.ini parsing, file handling, or cache management. When catching exceptions from the library, you can check the exception code against these constants to handle different error types programmatically.

    // Example of checking for a specific error code
    try {
        // ... browscap operations ...
    } catch (\BrowscapPHP\Exception $e) {
        if ($e->getCode() === \BrowscapPHP\Exception::INI_FILE_MISSING) {
            // Handle missing ini file
        }
    }
  8. Use the browscap:parse CLI command

    7.8.x

    The browscap:parse command allows you to analyze a specific user agent string and output the resulting browser capabilities in a pretty-printed JSON format.

    Usage

    Run the command followed by the user agent string you wish to analyze.

    Arguments

    • user-agent (Required): The user agent string to analyze.

    Options

    • --cache, -c (Optional): Specifies the directory where the cache files are located. If not provided, it uses the default cache folder configured for the application.

    Exit Codes

    • 0: Success
    • 11: PARSER_ERROR (Occurs if parsing fails or JSON encoding fails)
    php browscap:parse "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ..."
    
    # Example with custom cache directory
    php browscap:parse "Mozilla/5.0 ..." --cache /path/to/custom/cache
  9. Check for Browscap data updates via CLI

    7.8.x

    Use the browscap:check-update command to check if a newer version of the Browscap INI file is available on the remote host. This command compares your local cached version against the remote version.

    Options

    OptionShortDescriptionDefault
    --cache-cThe directory where the cache files are located.The default cache folder configured during command instantiation.

    Exit Codes

    When running this command in a script or CI/CD pipeline, you can check the exit code to determine the result:

    Exit CodeMeaning
    0Success (a new version was found or the check completed successfully).
    1NO_CACHED_VERSION: No cached version was found to compare against.
    2NO_NEWER_VERSION: The local version is up to date; no newer version is available.
    3ERROR_READING_CACHE: An error occurred while reading the local cache.
    4ERROR_READING_REMOTE_FILE: An error occurred while fetching the remote file.
    5GENERIC_ERROR: A generic error occurred during execution.
    # Check for updates using the default cache directory
    php bin/console browscap:check-update
    
    # Check for updates specifying a custom cache directory
    php bin/console browscap:check-update --cache=/path/to/your/cache
  10. Update local Browscap data via browscap:update

    7.8.x

    The browscap:update command fetches an updated INI file from a remote location, converts it into a PHP array format, and stores it locally. This process overwrites the current PHP file used for browser capability lookups.

    Options

    OptionShortDescription
    --remote-file-rThe specific browscap.ini file to download. Possible values: browscap-ini-lite.ini (via IniLoaderInterface::PHP_INI_LITE), browscap.ini (via IniLoaderInterface::PHP_INI), or browscap-ini-full.ini (via IniLoaderInterface::PHP_INI_FULL). Defaults to browscap.ini.
    --no-backupN/AIf provided, the command will not create a backup of the previously existing file before overwriting it.
    --cache-cThe directory path where the cache files are located. Defaults to the folder provided during the command's construction.

    Exit Codes

    CodeMeaning
    SUCCESSThe update completed successfully.
    ERROR_READING_CACHEAn error occurred while reading the cache (e.g., ErrorCachedVersionException).
    ERROR_READING_REMOTE_FILEAn error occurred while fetching the remote file (e.g., FetcherException).
    GENERIC_ERRORA generic error occurred during the update process.
  11. Fetch the latest browscap.ini via CLI

    7.8.x

    Use the browscap:fetch command to download an updated browscap.ini file from the remote host and save it to a local file. This is useful for keeping your browser capability data up to date.

    Arguments

    • file (optional): The local path where the browscap.ini file should be saved. If omitted, the command uses the default file path configured during setup.

    Options

    • --remote-file, -r (optional): Specifies which version of the browscap.ini file to download from the remote location. Possible values are:
      • php_ini_lite (default)
      • php_ini
      • php_ini_full (Note: These correspond to the constants defined in IniLoaderInterface).
    • --cache, -c (optional): The directory where cache files are located. If omitted, the command uses the default cache folder configured during setup.
    # Example: Fetch the default file to the default location
    php browscap fetch
    
    # Example: Fetch a specific remote version to a custom local file with a custom cache directory
    php browscap fetch my_custom_browscap.ini --remote-file php_ini_full --cache ./my_cache_dir