Izak the coder Izak the coder - 1 year ago 54
iOS Question

How to get php to tell if it run is on iOS or MacOS

I have been attempting to run two different variations of my website: one for desktop and one for mobile. I decided to make it work like this (using PHP): if on Windows, Mac, or other desktop OS, run this HTML. if on Android, iOS, etc. run that HTML. When I go to my website through Windows or Android, the HTML for the corresponding OS is run. But when I go to my website through an iPhone or MacBook, both the code for iPhone AND Mac is run, regardless of if the user is on an iPhone or MacBook: Here is the code I use:

<!--HTML for macOS -->

if(preg_match( '/macintosh|mac os x/i', $_SERVER['HTTP_USER_AGENT'])) {

echo' <!--some HTML--> '; } ?>

<!--HTML for iPhone-->


ifif(preg_match('/iphone/i', $_SERVER['HTTP_USER_AGENT'])) {

echo' <!--some HTML--> '; } ?>

If you want to observe the problem, go to bamfacts.tk Thank you!

Answer Source

Following Script will tell you if it is mac, iPhone, iPod or iPad.

// Apple detection array
    $Apple = array();
    $Apple['UA'] = $_SERVER['HTTP_USER_AGENT'];
    $Apple['Device'] = false;
    $Apple['Types'] = array('iPhone', 'iPod', 'iPad', 'Mac');
    foreach ($Apple['Types'] as $d => $t) {
        $Apple[$t] = (strpos($Apple['UA'], $t) !== false);
        $Apple['Device'] |= $Apple[$t];

// is this an Apple device?
    "<p>Apple device? ", ($Apple['Device'] ? 'true' : 'false'),
    "</p>n<p>iPhone? ", ($Apple['iPhone'] ? 'true' : 'false'),
    "</p>n<p>iPod? ", ($Apple['iPod'] ? 'true' : 'false'),
    "</p>n<p>iPad? ", ($Apple['iPad'] ? 'true' : 'false'),
    "</p>n<p>iPad? ", ($Apple['Mac'] ? 'true' : 'false'),

You can also do it with Java Script like following:

var Apple = {};
Apple.UA = navigator.userAgent;
Apple.Device = false;
Apple.Types = ["iPhone", "iPod", "iPad", "Mac"];
for (var d = 0; d < Apple.Types.length; d++) {
    var t = Apple.Types[d];
    Apple[t] = !!Apple.UA.match(new RegExp(t, "i"));
    Apple.Device = Apple.Device || Apple[t];

// is this an Apple device?
    "Apple device? " + Apple.Device +
    " \nis iPhone? " + Apple.iPhone +
    " \nis iPod? " + Apple.iPod +
    " \nis iPad? " + Apple.iPad +
    " \nis Mac? " + Apple.Mac

You can see the Javascript fiddle here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download