\$\begingroup\$
\$\endgroup\$
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
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)
asif ($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
-
\$\begingroup\$ I agree with Josay, this is not a good idea. You might want to look into responsive webdesign. \$\endgroup\$Nic Wortel– Nic Wortel2013年03月04日 01:26:13 +00:00Commented Mar 4, 2013 at 1:26
lang-php