在控制器laravel 5 php中获取useragent

时间:2016-03-28 17:26:08

标签: php laravel-5

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

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

4 个答案:

答案 0 :(得分:20)

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

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

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

答案 1 :(得分:3)

我认为您可以使用此代码

$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;

可能对此代码有用。或另一个尝试laravel包  https://github.com/antonioribeiro/tracker 要么 https://github.com/jenssegers/agent

答案 2 :(得分:0)

控制器外部可以尝试:

$server = \Request::server();
echo $server['HTTP_USER_AGENT']

答案 3 :(得分:0)

使用这种方式对我有用

echo Request::server('HTTP_USER_AGENT');

OR

echo $_SERVER['HTTP_USER_AGENT']