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

asked Mar 1, 2013 at 12:20
\$\endgroup\$

1 Answer 1

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!

answered Mar 1, 2013 at 12:43
\$\endgroup\$
1
  • \$\begingroup\$ I agree with Josay, this is not a good idea. You might want to look into responsive webdesign. \$\endgroup\$ Commented Mar 4, 2013 at 1:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.