10

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

Yves M.
  • 29,855
  • 23
  • 108
  • 144
shebelaw
  • 3,992
  • 6
  • 35
  • 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,360
  • 5
  • 27
  • 29
  • 1
    Do note that this is easily faked. – ceejayoz May 12 '11 at 17:15
  • @ceejayoz Yes of course. But I don't see any issues arising from that since the users would prob want the best experience and layout that fits the actual client being used. So they don't really have any interest in doing that. – Pepe May 12 '11 at 17:17
  • 1
    @ceejayoz Also I don't think the OP can do anything to prevent that on his end... – Pepe May 12 '11 at 17:19
  • 1
    Agreed. Just worth noting, as I've seen people try to restrict access in this manner and be surprised that it won't work for determined users. – ceejayoz May 12 '11 at 17:24
  • In the case of iPhone can I also get ESN, IME ID of the phone using JavaScript? – shebelaw May 12 '11 at 19:11
  • @user736659 I don't think so. – Pepe May 12 '11 at 19:55
  • 1
    @JJPA true, [offender](http://stackoverflow.com/users/1554910/kirankumar) is now suspended and the illegal answers deleted. – Shadow The GPT Wizard Mar 14 '13 at 12:40
  • @JJPA not my doing, just reporting it to prevent the author here from getting confused when the link you posted does not give him the answer you meant to show.. – Shadow The GPT Wizard Mar 14 '13 at 12:44
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
  • 242,470
  • 58
  • 448
  • 498
JD Audi
  • 1,067
  • 6
  • 18
  • 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.
  • 29,855
  • 23
  • 108
  • 144