Search code examples
phpjavascriptiphonehtmlmobile-safari

Detect iPhone Browser


is there a script to detect, if the visitor use iphone (whatever it's browser, may iphone Safari, iPhone for Opera or etc.)?

Then will shutdown some some of my JavaScript.

Thanks...


Solution

  • searching on the net there are two common ways of achieving this. My favorite though is in PHP its just so clean? wow. :D

    In PHP you can write

    <?php
    
    function isIphone($user_agent=NULL) {
        if(!isset($user_agent)) {
            $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        }
        return (strpos($user_agent, 'iPhone') !== FALSE);
    }
    
    if(isIphone()) {
        header('Location: http://www.yourwebsite.com/phone');
        exit();
    }
    
    // ...THE REST OF YOUR CODE HERE
    
    ?>
    

    and in javascript you can write

    var agent = navigator.userAgent;
    var isIphone = ((agent.indexOf('iPhone') != -1) || (agent.indexOf('iPod') != -1)) ;
    if (isIphone) {
        window.location.href = 'http://www.yourwebsite.com/phone';
    }
    

    Hope that helps.

    PK