👮 A PHP desktop/mobile user agent parser with support for Laravel, based on Mobiledetect

Overview

Agent

Latest Stable Version Total Downloads Build Status Coverage Status Donate

A PHP desktop/mobile user agent parser with support for Laravel, based on Mobile Detect with desktop support and additional functionality.

Installation

Install using composer:

composer require jenssegers/agent

Laravel (optional)

Add the service provider in config/app.php:

Jenssegers\Agent\AgentServiceProvider::class,

And add the Agent alias to config/app.php:

'Agent' => Jenssegers\Agent\Facades\Agent::class,

Basic Usage

Start by creating an Agent instance (or use the Agent Facade if you are using Laravel):

use Jenssegers\Agent\Agent;

$agent = new Agent();

If you want to parse user agents other than the current request in CLI scripts for example, you can use the setUserAgent and setHttpHeaders methods:

$agent->setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.13+ (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2');
$agent->setHttpHeaders($headers);

All of the original Mobile Detect methods are still available, check out some original examples at https://github.com/serbanghita/Mobile-Detect/wiki/Code-examples

Is?

Check for a certain property in the user agent.

$agent->is('Windows');
$agent->is('Firefox');
$agent->is('iPhone');
$agent->is('OS X');

Magic is-method

Magic method that does the same as the previous is() method:

$agent->isAndroidOS();
$agent->isNexus();
$agent->isSafari();

Mobile detection

Check for mobile device:

$agent->isMobile();
$agent->isTablet();

Match user agent

Search the user agent with a regular expression:

$agent->match('regexp');

Additional Functionality

Accept languages

Get the browser's accept languages. Example:

$languages = $agent->languages();
// ['nl-nl', 'nl', 'en-us', 'en']

Device name

Get the device name, if mobile. (iPhone, Nexus, AsusTablet, ...)

$device = $agent->device();

Operating system name

Get the operating system. (Ubuntu, Windows, OS X, ...)

$platform = $agent->platform();

Browser name

Get the browser name. (Chrome, IE, Safari, Firefox, ...)

$browser = $agent->browser();

Desktop detection

Check if the user is using a desktop device.

$agent->isDesktop();

This checks if a user is not a mobile device, tablet or robot.

Phone detection

Check if the user is using a phone device.

$agent->isPhone();

Robot detection

Check if the user is a robot. This uses jaybizzle/crawler-detect to do the actual robot detection.

$agent->isRobot();

Robot name

Get the robot name.

$robot = $agent->robot();

Browser/platform version

MobileDetect recently added a version method that can get the version number for components. To get the browser or platform version you can use:

$browser = $agent->browser();
$version = $agent->version($browser);

$platform = $agent->platform();
$version = $agent->version($platform);

Note, the version method is still in beta, so it might not return the correct result.

License

Laravel User Agent is licensed under The MIT License (MIT).

Security contact information

To report a security vulnerability, follow these steps.

Comments
  • Browser version detection fails for 'Opera' and 'IE' if user agent string doesnt match

    Browser version detection fails for 'Opera' and 'IE' if user agent string doesnt match

    The version function updates in 0.6.2 caused errors to be thrown when the user agent string passed in doesn't match the browser being tested if you test the version of 'Opera' or 'IE'. I didnt notice it on any other browsers.

    how to reproduce: $agent = new Agent(); $agent->setUserAgent('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)'); // IE user agent $agent->version('Opera');

    error info: https://github.com/jenssegers/agent/blob/41cd1fd6200a9b0d70db75133ee23064c9965980/src/Agent.php#L326

    'Array to string Conversion' jenssegers/agent/src/Agent.php(326): sprintf('#%s#is', Array)

    opened by mpetty 7
  • Add robot names

    Add robot names

    in Mobile_Detect.php on line 524:

        protected static $utilities = array(
            // Experimental. When a mobile device wants to switch to 'Desktop Mode'.
            // http://scottcate.com/technology/windows-phone-8-ie10-desktop-or-mobile/
            // https://github.com/serbanghita/Mobile-Detect/issues/57#issuecomment-15024011
            // https://developers.facebook.com/docs/sharing/best-practices
            'Bot'         => 'YandexBot|YandexImages|YandexVideo|YandexMedia|YandexBlogs|YandexFavicons|YandexWebmaster|YandexPagechecker|YandexImageResizer|YandexDirect|YaDirectFetcher|YandexCalendar|YandexSitelinks|YandexAdNet|YandexMetrika|YandexNews|YandexNewslinks|YandexCatalog|YandexAntivirus|YandexMarket|YandexVertis|YandexForDomain|YandexBot|Googlebot|facebookexternalhit|AdsBot-Google|Google Keyword Suggestion|Facebot|YandexBot|bingbot|ia_archiver|AhrefsBot|Ezooms|GSLFbot|WBSearchBot|Twitterbot|TweetmemeBot|Twikle|PaperLiBot|Wotbox|UnwindFetchor',
            'MobileBot'   => 'Googlebot-Mobile|AdsBot-Google-Mobile|YahooSeeker/M1A1-R2D2',
            'DesktopMode' => 'WPDesktop',
            'TV'          => 'SonyDTV|HbbTV', // experimental
            'WebKit'      => '(webkit)[ /]([\w.]+)',
            // @todo: Include JXD consoles.
            'Console'     => '\b(Nintendo|Nintendo WiiU|Nintendo 3DS|PLAYSTATION|Xbox)\b',
            'Watch'       => 'SM-V700',
        );
    

    it's only Yandex bots added

    YandexBot|YandexImages|YandexVideo|YandexMedia|YandexBlogs|YandexFavicons|YandexWebmaster|YandexPagechecker|YandexImageResizer|YandexDirect|YaDirectFetcher|YandexCalendar|YandexSitelinks|YandexAdNet|YandexMetrika|YandexNews|YandexNewslinks|YandexCatalog|YandexAntivirus|YandexMarket|YandexVertis|YandexForDomain|YandexBot
    
    opened by mokeev1995 7
  • Call To Undefinde Method

    Call To Undefinde Method

    For every method I try to use with the Facade class I get the following error:

    Call to undefined method Jenssegers\Agent\Facades\Agent::isMobile() (or similar )

    Can anyone tell me how to solve this? I did include the Facade and the ServiceProvider in my app/config/app.php

    opened by inov 7
  • Call to undefined method Application::bindShared

    Call to undefined method Application::bindShared

    I've run composer update to update my laravel 4.0.X version to fix the sessions problems.

    But now, when I try to run composer update or any php artisan command, I always receive this message:

    PHP Fatal error: Call to undefined method Illuminate\Foundation\Application::bindShared() in /var/www/myapp/vendor/jenssegers/agent/src/AgentServiceProvider.php on line 31

    This line, 31 is the following:

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bindShared('agent', function($app)
        {
            return new Agent;
        });
    }
    

    Do you know how can I fix it?? It is really important

    Thanks

    opened by vtellez 7
  • Platform returns iOS on my Macbook Air

    Platform returns iOS on my Macbook Air

    I'm using Laravel 4.1 and the latest version of Laravel-Agent (says 4.* in composer.json) and when I try:

    var_dump(Agent::platform()) 
    

    it says

    string(3) "iOS"
    

    And also Agent::isMobile() says true.

    Any ideas on this?

    opened by rickyryden 6
  • Laravel 5.4 support

    Laravel 5.4 support

    Minor issue, support for "share" has been dropped in 5.4.

    public function register()
    {
        $this->app['agent'] = $this->app->share(function ($app)
        {
            return new Agent($app['request']->server->all());
        });
    }
    

    Ref: https://laravel.com/docs/5.4/upgrade

    I believe, in the case of Agent, it should be swapped out for singleton.

    Error currently:

    > php artisan optimize
    
    
      [Symfony\Component\Debug\Exception\FatalThrowableError]
      Call to undefined method Illuminate\Foundation\Application::share()
    
    opened by cjke 5
  • create mac address function

    create mac address function

    this function work get client MAC address by a access on a website or project. This function call $agent->macAddress();

    This function add Agent.php and this function simple call $agent->macAddress(); it show mack address for client . it is 100% work i check . please check and add this code .

    this code is ok then functon write read me file

    $agent->macAddress();

    Thanks karim

    opened by karim-khan 5
  • Add further patterns to robots array

    Add further patterns to robots array

    Furthermore, Agent::$robots is now a list, the associative array didn't seem necessary(?). Credit due to https://github.com/monperrus/crawler-user-agents for the data.

    opened by billygrant24 5
  • Broken on Laravel 5 (gasp!)

    Broken on Laravel 5 (gasp!)

    Although it's a bit taboo right now - this is of course broken on L5.

    Easy to fix though. Remove the boot method from your provider. It's not needed. The package does not require any config or anything.

    I have a fork and did just that and have been using it happily for probably a month.

    Cheers!

    opened by RyanThompson 5
  • Same problem: isMobile does not exists

    Same problem: isMobile does not exists

    Hi.

    I was trying to use your lib, but the method isMobile() was not available (the very same problem than this link: https://github.com/jenssegers/agent/issues/20).

    So, I used MobileDetect directly. I do not know what I did wrong, but MobileDirect worked fine.

    Thank you.

    opened by ppalmeida 4
  • Fixed bug when testing browser version for Opera or IE #138

    Fixed bug when testing browser version for Opera or IE #138

    https://github.com/jenssegers/agent/issues/138

    This fixes an issue with detecting the browser version if the mobile detect library returns an array of parameters instead of a string.

    There may be a better way to handle this so that the preg_match in the version method doesnt have duplicated items in it, but this should work to prevent any errors if it gets that far.

    opened by mpetty 3
  • [NEW] Detect Device Details with Detective API

    [NEW] Detect Device Details with Detective API

    Hello guys,

    Detecting the device details of your users is now easier than ever with Detective API. Our API is powered by AI and makes detecting devices easy and effortless. Check it out

    opened by realtechspecs 0
  • agent Detection not working with redirect

    agent Detection not working with redirect

    Hello agent not working when use laravel redirect

    id normal using it's working :

    Route::get('', [HomeController::class, 'index'])->name('home');

    But when using redirect, it's not working

    Route::get('/ddd', function () {
        return redirect('/');
    });
    

    laravel 8

    opened by ebeliejinfren 0
  • Package Abandoned?

    Package Abandoned?

    Looking at the activity on this repo I just wanted to ask if it has been abandoned? The StyleCI flag has been failing for over a year and no code has been committed or merged in nearly 9 months.

    Love the package and just wondered if I spend some time writing PRs if they will be merged or not.

    opened by MaxGiting 2
  • Update PHP CS Fixer config file name

    Update PHP CS Fixer config file name

    I was trying to fix the failing StyleCI flag.

    It seems that everything after June 14th, 2020 started failing which from this blog looks to be around the time that StyleCI changed its default behaviour to disable "risky" fixers. Which also matches the warning on all failure messages from StyleCI.

    https://blog.styleci.io/platform-improvements/

    I cannot see why the .yml file settings of risky: true has not fixed or even changed the error message. StyleCI does mention you can override the .yml file settings in your StyleCI dashboard. I don't know if you have done that.

    opened by MaxGiting 0
Releases(v2.6.4)
Owner
Jens Segers
Head of Engineering at CHEQROOM
Jens Segers
Mobile_Detect is a lightweight PHP class for detecting mobile devices (including tablets). It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment.

Motto: "Every business should have a detection script to detect mobile readers." About Mobile Detect is a lightweight PHP class for detecting mobile d

Şerban Ghiţă 10.2k Jan 4, 2023
A PHP parser for TOML

TOML parser for PHP A PHP parser for TOML compatible with TOML v0.4.0. Support: Installation Requires PHP >= 7.1. Use Composer to install this package

Yo! Symfony 175 Dec 26, 2022
php-crossplane - Reliable and fast NGINX configuration file parser and builder

php-crossplane Reliable and fast NGINX configuration file parser and builder ℹ️ This is a PHP port of the Nginx Python crossplane package which can be

null 19 Jun 30, 2022
A PHP string manipulation library with multibyte support. Compatible with PHP 5.4+, PHP 7+, and HHVM.

A PHP string manipulation library with multibyte support. Compatible with PHP 5.4+, PHP 7+, and HHVM. s('string')->toTitleCase()->ensureRight('y') ==

Daniel St. Jules 2.5k Dec 28, 2022
A PHP string manipulation library with multibyte support

A PHP string manipulation library with multibyte support. Compatible with PHP 5.4+, PHP 7+, and HHVM. s('string')->toTitleCase()->ensureRight('y') ==

Daniel St. Jules 2.5k Jan 3, 2023
:accept: Stringy - A PHP string manipulation library with multibyte support, performance optimized

?? Stringy A PHP string manipulation library with multibyte support. Compatible with PHP 7+ 100% compatible with the original "Stringy" library, but t

Lars Moelleken 144 Dec 12, 2022
Library for free use Google Translator. With attempts connecting on failure and array support.

GoogleTranslateForFree Packagist: https://packagist.org/packages/dejurin/php-google-translate-for-free Library for free use Google Translator. With at

Yurii De 122 Dec 23, 2022
A tiny PHP class-based program to analyze an input file and extract all of that words and detect how many times every word is repeated

A tiny PHP class-based program to analyze an input file and extract all of that words and detect how many times every word is repeated

Max Base 4 Feb 22, 2022
SNIA SSS PTS test suite based on SNIA's Solid State Storage Performance Test Specification for Transcend products

SNIA-SSS-PTS ABSTRACT SNIA SSS PTS describes a solid state storage device-level performance test methodology, test suite and reporting format intended

Transcend Information, Inc. 6 Nov 2, 2022
"結巴"中文分詞:做最好的 PHP 中文分詞、中文斷詞組件。 / "Jieba" (Chinese for "to stutter") Chinese text segmentation: built to be the best PHP Chinese word segmentation module.

jieba-php "結巴"中文分詞:做最好的 PHP 中文分詞、中文斷詞組件,目前翻譯版本為 jieba-0.33 版本,未來再慢慢往上升級,效能也需要再改善,請有興趣的開發者一起加入開發!若想使用 Python 版本請前往 fxsjy/jieba 現在已經可以支援繁體中文!只要將字典切換為 bi

Fukuball Lin 1.2k Dec 31, 2022
highlight.php is a server-side syntax highlighter written in PHP that currently supports 185 languages

highlight.php is a server-side syntax highlighter written in PHP that currently supports 185 languages. It's a port of highlight.js by Ivan Sagalaev that makes full use of the language and style definitions of the original JavaScript project.

Geert Bergman 633 Dec 27, 2022
Converts a string to a slug. Includes integrations for Symfony, Silex, Laravel, Zend Framework 2, Twig, Nette and Latte.

cocur/slugify Converts a string into a slug. Developed by Florian Eckerstorfer in Vienna, Europe with the help of many great contributors. Features Re

Cocur 2.8k Dec 22, 2022
A PHP library for generating universally unique identifiers (UUIDs).

ramsey/uuid A PHP library for generating and working with UUIDs. ramsey/uuid is a PHP library for generating and working with universally unique ident

Ben Ramsey 11.9k Jan 8, 2023
A lightweight php class for formatting sql statements. Handles automatic indentation and syntax highlighting.

SqlFormatter A lightweight php class for formatting sql statements. It can automatically indent and add line breaks in addition to syntax highlighting

Jeremy Dorn 3.9k Jan 1, 2023
A sane interface for php's built in preg_* functions

Making regex great again Php's built in preg_* functions require some odd patterns like passing variables by reference and treating false or null valu

Spatie 1.1k Jan 4, 2023
A fast PHP slug generator and transliteration library that converts non-ascii characters for use in URLs.

URLify for PHP A fast PHP slug generator and transliteration library, started as a PHP port of URLify.js from the Django project. Handles symbols from

Aband*nthecar 667 Dec 20, 2022
🉑 Portable UTF-8 library - performance optimized (unicode) string functions for php.

?? Portable UTF-8 Description It is written in PHP (PHP 7+) and can work without "mbstring", "iconv" or any other extra encoding php-extension on your

Lars Moelleken 474 Dec 22, 2022
ColorJizz is a PHP library for manipulating and converting colors.

#Getting started: ColorJizz-PHP uses the PSR-0 standards for namespaces, so there should be no trouble using with frameworks like Symfony 2. ###Autolo

Mikeemoo 281 Nov 25, 2022
🔡 Portable ASCII library - performance optimized (ascii) string functions for php.

?? Portable ASCII Description It is written in PHP (PHP 7+) and can work without "mbstring", "iconv" or any other extra encoding php-extension on your

Lars Moelleken 380 Jan 6, 2023