10

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

Yves M.
  • 28,433
  • 22
  • 100
  • 135
shebelaw
  • 3,772
  • 6
  • 34
  • 48

3 Answers3

8

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"];
Pepe
  • 6,251
  • 5
  • 26
  • 29
8

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

Dave DeLong
  • 241,045
  • 58
  • 447
  • 497
JD Audi
  • 1,049
  • 6
  • 17
  • 37
0

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.

Yves M.
  • 28,433
  • 22
  • 100
  • 135