PHP code example of larva / agent

1. Go to this page and download the library: Download larva/agent library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

larva / agent example snippets


use Agent;

if (Agent::isMobile()) {
    // 移动端逻辑
}

'providers' => [
    Larva\Agent\AgentServiceProvider::class,
],

'aliases' => [
    'Agent' => Larva\Agent\Facades\Agent::class,
],

use Larva\Agent\Agent;

$agent = new Agent();

$agent->setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15');

// 或者一次性注入完整的 HTTP 头(会自动从中提取 User-Agent)
$agent->setHttpHeaders($headers);

$agent = new Agent(config: ['autoInitOfHttpHeaders' => false]);
$agent->setUserAgent($userAgent);

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

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

$agent->isMobile();   // 手机或平板
$agent->isTablet();   // 平板
$agent->isPhone();    // 手机(移动设备且非平板)
$agent->isDesktop();  // 桌面设备(非移动、非平板、非爬虫)
$agent->isRobot();    // 爬虫 / 机器人

$type = $agent->deviceType();

$agent->match('regexp', $userAgent);

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

// 也可以直接传入 header 值
$languages = $agent->languages('nl-nl,nl;q=0.9,en-us;q=0.5');

$device = $agent->device();

$platform = $agent->platform();

$browser = $agent->browser();

$robot = $agent->robot();
// 'Googlebot'

$version = $agent->version($agent->browser());
// '124.0.0.0'

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

// 以浮点数返回,便于比较
$version = $agent->version($agent->browser(), Agent::VERSION_TYPE_FLOAT);
// 124.0