在 controller laravel 5 php 中获取 useragent

2022-08-30 17:32:05

我正在使用laravel 5.0。如何从控制器中的$request获取用户代理?

public function index(Request $request)
{
    $useragent = $request->userAgent; // ????
    return $useragent;
}

答案 1

您可以使用以下任一方式:

$ua = $request->server('HTTP_USER_AGENT');

$ua = $request->header('User-Agent');

答案 2

我认为你可以使用这个代码

$user_agent = $request->header('User-Agent');
    $bname = 'Unknown';
    $platform = 'Unknown';

    //First get the platform?
    if (preg_match('/linux/i', $user_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $user_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $user_agent)) {
        $platform = 'windows';
    }

    echo $platform;

    echo "<br>";


    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$user_agent) && !preg_match('/Opera/i',$user_agent))
    {
        $bname = 'Internet Explorer';
        $ub = "MSIE";
    }
    elseif(preg_match('/Firefox/i',$user_agent))
    {
        $bname = 'Mozilla Firefox';
        $ub = "Firefox";
    }
    elseif(preg_match('/Chrome/i',$user_agent))
    {
        $bname = 'Google Chrome';
        $ub = "Chrome";
    }
    elseif(preg_match('/Safari/i',$user_agent))
    {
        $bname = 'Apple Safari';
        $ub = "Safari";
    }
    elseif(preg_match('/Opera/i',$user_agent))
    {
        $bname = 'Opera';
        $ub = "Opera";
    }
    elseif(preg_match('/Netscape/i',$user_agent))
    {
        $bname = 'Netscape';
        $ub = "Netscape";
    }

    echo $bname;

可能是它有用这个代码。或者另一个尝试 https://github.com/antonioribeiro/tracker 或 https://github.com/jenssegers/agent 的laravel包


推荐