hisorange/browser-detect

repository·stable·Indexed 22 days ago

https://github.com/hisorange/browser-detect

A PHP package to identify visitor details including device type (mobile, tablet, desktop), operating system, and browser vendor. It can be used as a standalone library via the Parser class or integrated into Laravel using the Browser facade and custom Blade directives (@mobile, @tablet, @desktop, @browser).

Tokens
5.5K
Snippets
13
Records
17
Agent score
76%

What's inside hisorange-browser-detect

  1. Use Browser detection in Laravel

    stable

    In a Laravel environment, you can use the Browser facade to identify device types, operating systems, and browser vendors. This works in both controllers and Blade templates.

    In PHP code

    Use the Browser facade to perform checks:

    use Browser;
    
    // Device type checks
    $isMobile = Browser::isMobile();
    Browser::isTablet();
    Browser::isDesktop();
    
    // Bot detection
    if (Browser::isBot()) {
        // Logic for bots
    }
    
    // Browser vendor checks
    if (Browser::isFirefox() || Browser::isOpera()) {
        // Logic for specific browsers
    }
    
    // OS checks
    if (Browser::isAndroid()) {
        // Logic for Android
    } elseif (Browser::isMac() && Browser::isMobile()) {
        // Logic for iOS
    }

    In Blade templates

    The package provides custom Blade directives for easy conditional rendering:

    @mobile
        <p>This is the MOBILE template!</p>
    @endmobile
    
    @tablet
        <p>This is the TABLEK template!</p>
    @endtablet
    
    @desktop
        <p>This is the DESKTOP template!</p>
    @enddesktop
    
    {{-- You can also use any result key via the @browser directive --}}
    @browser('isBot')
        <p>Bots are identified too :)</p>
    @endbrowser
    use Browser;
    
    // Determine the user's device type is simple as this:
    $isMobile = Browser::isMobile();
    Browser::isTablet();
    Browser::isDesktop();
    
    if (Browser::isMobile()) {
      // Redirect to the mobile version of the site.
    }
    
    // Every wondered if it is a bot who loading Your page?
    if (Browser::isBot()) {
        echo 'No need to wonder anymore!';
    }
    
    // Check for common vendors.
    if (Browser::isFirefox() || Browser::isOpera()) {
        $response .= '<script src="firefox-fix.js"></script>';
    }
    
    // Sometimes You may want to serve different content based on the OS.
    if (Browser::isAndroid()) {
        $response .= '<a>Install our Android App!</a>';
    } elseif (Browser::isMac() && Browser::isMobile()) {
        $response .= '<a>Install our iOS App!</a>';
    }
  2. Use browser-detect in Standalone PHP mode

    stable

    You can use the library without Laravel by using the Parser class as a static object. This is useful for non-Laravel PHP applications.

    use hisorange\BrowserDetect\Parser as Browser;
    
    if (Browser::isLinux()) {
        // Works as well!
    }
  3. Configure cache for Standalone mode

    stable

    In standalone mode, you can apply custom configuration (such as cache intervals) by passing an options array to the Parser constructor:

    use hisorange\BrowserDetect\Parser;
    
    $browser = new Parser(null, null, [
        'cache' => [
            'interval' => 86400 // This will override the default configuration.
        ]
    ]);
    
    $result = $browser->detect();
  4. Configure browser-detect in Laravel

    stable

    To publish the configuration file in a Laravel project, run the following Artisan command. This will copy the config file to ~/app/config/browser-detect.php:

    php artisan vendor:publish
    # Will copy a config file to ~/app/config/browser-detect.php
    php artisan vendor:publish
  5. Publish the browser-detect configuration file

    stable

    To customize the package behavior, you can publish the configuration file to your application's config directory. Run the following Artisan command in your terminal:

    php artisan vendor:publish --tag=config

    This will copy the configuration from the package to config/browser-detect.php.

  6. Parse custom User Agent strings

    stable

    By default, the detect() method parses the current user's agent. To parse a specific User Agent string, use the parse() method:

    // Get result for current user
    $result = Browser::detect();
    
    // Get details from a specific User Agent string
    $result = Browser::parse('Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14');

    Performance Note: The parser uses an in-memory runtime cache for multiple calls in a single page load and uses the application's cache to persist results for approximately one week, making detection extremely efficient.

    // When You call the detect function You will get a result object, from the current user's agent.
    $result = Browser::detect();
    
    // If You wanna get browser details from a user agent other than the current user call the parse function.
    $result = Browser::parse('Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14');
  7. Reference: Browser API methods

    stable

    Every call on the Browser facade is proxied to a result object. The following methods are available:

    CallResponseInternal Type
    Browser::userAgent()Current visitor's HTTP_USER_AGENT string.(string)
    Browser::isMobile()Is this a mobile device.(boolean)
    Browser::isTablet()Is this a tablet device.(boolean)
    Browser::isDesktop()Is this a desktop computer.(boolean)
    Browser::isBot()Is this a crawler / bot.(boolean)
    Browser::deviceType()Enumerated response for [Mobile, Tablet, Desktop, and Bot](string)
    Browser related
    Browser::browserName()Browser's human friendly name (e.g., Firefox 3.6).(string)
    Browser::browserFamily()Browser's vendor (e.g., Chrome, Firefox, Opera).(string)
    Browser::browserVersion()Browser's human friendly version string.(string)
    Browser::browserVersionMajor()Browser's major version.(integer)
    Browser::browserVersionMinor()Browser's minor version.(integer)
    Browser::browserVersionPatch()Browser's patch version.(integer)
    Browser::browserEngine()Browser's engine (e.g., Blink, WebKit, Gecko).(string)
    OS related
    Browser::platformName()OS's human friendly name (e.g., Windows XP).(string)
    Browser::platformFamily()OS's vendor (e.g., Linux, Windows, Mac).(string)
    Browser::platformVersion()OS's human friendly version.(integer)
    Browser::platformVersionMajor()OS's major version.(integer)
    Browser::platformVersionMinor()OS's minor version.(integer)
    Browser::platformVersionPatch()OS's patch version.(integer)
    OS extended
    Browser::isWindows()Is this a windows operating system.(boolean)
    Browser::isLinux()Is this a linux based operating system.(boolean)
    Browser::isMac()Is this an iOS or Mac based operating system.(boolean)
    Browser::isAndroid()Is this an Android operating system.(boolean)
    Device related
    Browser::deviceFamily()Device's vendor (e.g., Samsung, Apple).(string)
    Browser::deviceModel()Device's brand name (e.g., iPad, iPhone).(string)
    Browser vendor related
    Browser::isChrome()Is this a chrome browser.(boolean)
    Browser::isFirefox()Is this a firefox browser.(boolean)
    Browser::isOpera()Is this an opera browser.(boolean)
    Browser::isSafari()Is this a safari browser.(boolean)
    Browser::isIE()Checks if the browser is some kind of Internet Explorer.(boolean)
    Browser::isIEVersion()Compares to a given IE version.(boolean)
    Browser::isEdge()Is this a microsoft edge browser.(boolean)
    Miscellaneous
    Browser::isInApp()Check for browsers inside applications (e.g. android webview).(boolean)
  8. Access browser and device details via the Result class

    stable

    The hisorange\BrowserDetect\Result class is the object returned after a detection process. It provides a safe, structured way to access parsed information about the user agent, including browser type, device category, platform, and versioning.

    Key capabilities include:

    • Device Detection: Check if the user is on isMobile(), isTablet(), isDesktop(), or isBot().
    • Browser Detection: Check for specific browsers like isChrome(), isFirefox(), isOpera(), isSafari(), isEdge(), or isIE().
    • Platform Detection: Check for operating systems like isWindows(), isLinux(), isMac(), or isAndroid().
    • Version Comparison: Use isIEVersion(int $version, string $operator) to check Internet Explorer versions using standard comparison operators (e.g., '=', '>', '<').
    • Data Export: Convert the result to an array via toArray() or serialize it to JSON via jsonSerialize().
    // Assuming $result is an instance of hisorange\BrowserDetect\Result
    
    if ($result->isMobile()) {
        echo "User is on a mobile device";
    }
    
    if ($result->isChrome()) {
        echo "Browser: " . $result->browserName();
    }
    
    if ($result->isIEVersion(11, '>=')) {
        echo "User is using IE 11 or newer";
    }
    
    echo "Device Type: " . $result->deviceType(); // Returns 'Mobile', 'Tablet', 'Bot', 'Desktop', or 'Unknown'
  9. Use the Payload class to manage detection state

    stable

    The Payload class acts as a state carrier object that moves through the detection pipeline. It holds the initial User Agent string and accumulates detection results in an internal store. You can interact with it using getValue and setValue to retrieve or add specific detection data, and toArray to export the complete set of detected information.

    use hisorange\BrowserDetect\Payload;
    
    // Initialize with the User Agent string
    $payload = new Payload('Mozilla/5.0...');
    
    // Set a value in the detection store
    $payload->setValue('browser', 'Chrome');
    
    // Retrieve a value
    $browser = $payload->getValue('browser'); // returns 'Chrome'
    
    // Get the full detection results as an array
    $results = $payload->toArray();
    // $results contains ['browser' => 'Chrome', 'userAgent' => 'Mozilla/5.0...']
  10. BrowserDetect stage logic and payload keys

    stable

    The BrowserDetect stage is responsible for refining the detection payload by resolving device types, identifying browser vendors, formatting human-readable names, and detecting in-app environments.

    When this stage processes a PayloadInterface, it sets or updates the following keys in the payload:

    Device Type Resolution

    • isMobile: true if the device is mobile.
    • isTablet: true if the device is a tablet.
    • isDesktop: true if the device is a desktop.
    • isBot: true if the User Agent contains 'Prerender'.

    Browser Identification

    • isChrome, isFirefox, isOpera, isSafari, isIE, isEdge: Boolean flags based on the browserFamily.
    • browserVersion: A human-readable string (e.g., 12.1) constructed from major, minor, and patch versions.
    • browserName: A combined string of browserFamily and browserVersion.

    Platform Identification

    • isWindows, isAndroid, isMac, isLinux: Boolean flags based on the platformFamily.
    • platformVersion: A human-readable string constructed from major, minor, and patch versions.
    • platformName: A combined string of platformFamily and platformVersion.

    Special Detection

    • isInApp: true if the User Agent matches known in-app patterns (e.g., WebView, Twitter, MicroMessenger, or specific iOS/Android in-app patterns).
  11. Device and Platform detection via DeviceDetector stage

    stable

    The DeviceDetector stage is used to identify the device type, brand, model, operating system (platform), and browser details from a User Agent string. It is designed to skip bot detection to focus on actual user devices.

    When this stage processes a payload, it populates the following keys in the payload:

    Platform Information

    • platformFamily: The name of the operating system.
    • platformVersion: The full version string.
    • platformVersionMajor: The major version number.
    • platformVersionMinor: The minor version number.
    • platformVersionPatch: The patch version number.

    Browser Information

    • browserFamily: The name of the browser.
    • browserEngine: The browser engine used.
    • browserVersion: The full version string.
    • browserVersionMajor: The major version number.
    • browserVersionMinor: The minor version number.
    • browserVersionPatch: The patch version number.

    Device Information

    • isDesktop: true if the device type is desktop.
    • isTablet: true if the device type is tablet.
    • isMobile: true if the device type is smartphone, feature phone, or phablet.
    • deviceFamily: The full name of the device brand.
    • deviceModel: The specific model of the device.