auto-switch (mobile) theme based on User-Agent

23 Apr 2010

I dislike the idea of auto-switching to mobile themes in general. I want the user to have the choice considering the fact that smartphones have now more power, bigger screens are wi-fi capable (no 3G costs).

Sometimes though, it is a good practice. Especially in the case of arstechnica.com, which has a design-perfect mobile website. If you are developing websites using Drupal, there are some good modules: Mobile Tools and Browscap.

For simpler constructions like photodiary.gr you can code simple and clean.

Pixelpost auto-switch theme based on User-Agent example

in httpdocs/index.php (pixelpost root directory) bellow the

<?php
// get config
if($cfgrow = sql_array("SELECT * FROM ".$pixelpost_db_prefix."config"))
{
   
$upload_dir = $cfgrow['imagepath'];
}else{
   
$extra_message= "Coming Soon. Not Installed Yet. Cause #1";
   
show_splash($extra_message,"templates");

}
?>

add

<?php
$browser
=
strpos($_SERVER['HTTP_USER_AGENT'],"Windows CE") |  strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry") |  strpos($_SERVER['HTTP_USER_AGENT'],"Opera Mini") |  strpos($_SERVER['HTTP_USER_AGENT'],"Opera Mobi") |  strpos($_SERVER['HTTP_USER_AGENT'],"S60") |  strpos($_SERVER['HTTP_USER_AGENT'],"iPhone") |  strpos($_SERVER['HTTP_USER_AGENT'],"Android") |  strpos($_SERVER['HTTP_USER_AGENT'],"SymbianOS"); if ($browser) { $cfgrow['template'] = 'mobile'; $cfgrow['maxpthumb'] = 24; }
?>

The algorythm is basicaly

$browser = User Agent or another User Agent or etc;

if ($browser) { then change theme }

and the logic can be applied to other similar cases

 

How to find the USER_AGENT

create a test.php at the httpdocs/ and add the following

<?php
echo "<table border=\"1\">";
echo
"<tr><td>" .$_SERVER['HTTP_USER_AGENT'] ."</td><td>HTTP_USER_AGENT</td></tr>";
echo
"<tr><td>" .$_SERVER['REQUEST_URI'] ."</td><td>REQUEST_URI</td></tr>";
echo
"</table>"
?>

Point your/the mobile browser to domain/test.php and get the info.
You can get the USER_AGENT for iPhone, Android, Symbian S60, BlackBerry, Opera mini and mobile, Windows CE from the above pixelpost example code. As you can see, you don't have to use the full USER_AGENT string, but choose only a word that is unique for identifying the mobile browser (as in Nokia Symbian S60 case).

Related Items

Website