How do I detect mobile clients on my web server?

2019-02-21 13:31发布

问题:

When http request comes to my server, how do I detect if it is from iphone, android, or other devices?

回答1:

You can grab the User Agent. That tells what browser type it is (iphone, chrome, ie, anything)

To help you:

http://whatsmyuseragent.com/

http://en.wikipedia.org/wiki/User_agent



回答2:

You need to check the header of the HTTP request. You can find both the OS and the browser being used in the "User-Agent" field.

If you are using javascript then use the navigator object

navigator.userAgent

If you are using php then you can access the HTTP header

$userAgent = $_SERVER["HTTP_USER_AGENT"];


回答3:

As @dave-delong states in his response you can use the User-Agent HTTP header.

But User-Agent can be quite hard to parse.

I recommend you to use third party libraries for parsing User-Agent and detecting mobile.

On Node.js

Apparently OP uses Node.js and then can use mobiledetect.js (demo).

Detect the device by comparing patterns against a given User-Agent string (phone, tablet, desktop, mobile grade, os, versions).

const MobileDetect = require('mobile-detect');

const md = new MobileDetect(req.headers['user-agent']);

console.log(md.mobile());   // 'Sony'
console.log(md.phone());    // 'Sony'
console.log(md.tablet());   // null

On PHP

On a PHP server mobiledetect (demo).

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.