1
\$\begingroup\$

I'm new to PHP and I would like to redirect the visitors of my website based on their operating system. Below is my solution. Is there anything that needs to be optimized?

<?php
    // MOBILE
    $android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
    $blackberry = strpos($_SERVER['HTTP_USER_AGENT'],"BB10");
    $ios = strpos($_SERVER['HTTP_USER_AGENT'],"iOS");
    // DESKTOP
    $windows = strpos($_SERVER['HTTP_USER_AGENT'],"Windows");
    $mac = strpos($_SERVER['HTTP_USER_AGENT'],"Mac");

    // REDIRECTS 
    // MOBILE
    if ($android == true) 
    { 
    header('Location: http://www.example.com/android');
    } 
    else if ($blackberry == true) 
    { 
    header('Location: http://www.example.com/blackberry');
    }
    else if ($ios == true) 
    { 
    header('Location: http://www.example.com/ios');
    }
    // DESKTOP
    else if ($windows == true) 
    { 
    header('Location: http://www.example.com/windows');
    }
    else if ($mac == true) 
    { 
    header('Location: http://www.example.com/mac');
    }
    ?>

Thanks. Patrick

\$\endgroup\$
2
\$\begingroup\$

Before anything, I'll let you search on the web why this might not be such a good idea and I'll just focus on the code.

  • You probably should retrieve $_SERVER['HTTP_USER_AGENT'] and store it in a variable in order to avoid repeated code. Also, you might want to check if the variable is set properly before accessing it to avoid warnings/errors.
  • You can rewrite if ($variable == true) as if ($variable)
  • You could avoid the boilerplate and repeated code if you were storing the interesting parts of your logic in an array and write the common parts only once :
    $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    $redir = array(
        "Android" => 'android',
        "BB10"    => 'blackberry',
        "iOS"     => 'ios',
        "Windows" => 'windows',
        "Mac"     => 'mac'
    );
    if (isset($redir[$ua]))
    {
        header('Location: http://www.example.com/' . $redir[$ua]);
    }

I hope this helps!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I agree with Josay, this is not a good idea. You might want to look into responsive webdesign. \$\endgroup\$ – Nic Wortel Mar 4 '13 at 1:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.