Server side sniffing in PHP for mobile devices
Posted by Jesse Rodgers on March 12, 2007 at 12:25 AM
If you go to the UW home page in a Blackberry or Nokia device you will notice that you get a very different page than what you see on your laptop. I mentioned this change back in January. A few people have asked about how we are doing that and given a post on the quirksmode blog suggesting a similar idea I figure I should post the code for all.
In a PHP script that is included in the top of the index.php file, all we do is:
- $ua = $_SERVER[‘HTTP_USER_AGENT’];
- if (stristr($ua, “Windows CE”) || stristr($ua, “AvantGo”) || stristr($ua, “Mazingo”) || stristr($ua, “Mobile”) || stristr($ua, “T68”) || stristr($ua, “Syncalot”) || stristr($ua, “Blazer”) || stristr($ua,’BlackBerry’) || stristr($ua,’Opera Mini’) || stristr($ua,’Nokia’) || stristr($ua,’SymbianOS’ ))
- {
- $DEVICE_TYPE=”MOBILE”;
- }
- if (isset($DEVICE_TYPE) && $DEVICE_TYPE==”MOBILE”)
- {
- $location=’http://www.uwaterloo.ca/mobile.php’;
- header (‘Location: ’.$location);
- }
A bit of a headache was getting the right info for the user agent. Each device displays odd information that either tells you the browser or the device or the OS. A little trial an error was needed here.
Then in the mobile.php (uses the xhtml-mobile10.dtd) file we have minimal links but when clicked they parse content from the main index.php page. No duplication of content, just optimized. I will post more on that later ;)