-
-
Notifications
You must be signed in to change notification settings - Fork 1
UserAgent Component
Browser detection for PHP. It uses a simple and fast algorithm to recognize major browsers.
This component was part of this library in versions prior to 2.0. It is now deprecated in favor of the external UserAgent project.
PHP provides a native function to detect the user browser: get_browser(). This function requires the browscap.ini file which is 300KB+ in size. Loading and processing this file impacts the script performance. And sometimes, the production server just doesn't provide browscap.ini.
Although get_browser() surely provides excellent detection results, in most cases a much simpler method can be just as effective. Webtools UserAgent has the advantage of being compact and easy to extend. It is performant as well, since it doesn't do any iteration or recursion.
Include the classes or rely on Composer's autoloader. Then create the UserAgent
object.
use FlameCore\Webtools\UserAgent;
// Create a user agent object
$userAgent = new UserAgent();
// Interrogate the user agent
$userAgent->getBrowserName(); // firefox
$userAgent->getBrowserVersion(); // 3.6
$userAgent->getBrowserEngine(); // gecko
$userAgent->getOperatingSystem(); // linux
When you create a UserAgent
object, the current user agent string is used. You can specify another user agent string:
// use another user agent string
$userAgent = new UserAgent('msnbot/2.0b (+http://search.msn.com/msnbot.htm)');
$userAgent->getBrowserName(); // msnbot
// use current user agent string
$userAgent = new UserAgent($_SERVER['HTTP_USER_AGENT']);
// which is equivalent to:
$userAgent = new UserAgent();
By default, the class UserAgentStringParser
is used to analyze the user agent string. You can replace the parser instance and customize it to match your needs:
// create a custom user agent string parser
class MyUserAgentStringParser extends UserAgentStringParser
{
// override methods
}
// inject the custom parser when creating a user agent:
$parser = new MyUserAgentStringParser();
$userAgent = new UserAgent(null, $parser);
If you found a browser or operating system this library fails to recognize, feel free to submit an issue. Please provide the user agent string. And well, if you also want to provide the patch, that's even better.