I'm building a mobile version of my site, and at this point, creating an alternate stylesheet would suffice to make the site adept for mobile devices. I want to use a user agent detection PHP script to detect the platform, and switch stylesheets accordingly. Is there any way to do that?
-
1See this: http://stackoverflow.com/questions/3817155/php-mobile-browser-detection Then just have an if/else statement echoing the HTML code used to call the stylesheet. – Palladium Jun 29 '12 at 03:21
-
That's good, but the part I'm having trouble with is swapping stylesheets. – Jules Jun 29 '12 at 03:23
-
3Why not use [CSS media queries](http://css-tricks.com/css-media-queries/) and style to the screen size, not the user agent – Phil Jun 29 '12 at 03:28
-
Media queries are the way to go. – prodigitalson Jun 29 '12 at 03:30
-
That's actually brilliant. Thanks! – Jules Jun 29 '12 at 03:31
3 Answers
You might want to try out a librabry to check if its a mobile device then you can try out this library: http://code.google.com/p/php-mobile-detect/ (this also supports detecting specific OSes)
and then have code like
if($detect->isiOS()){
echo <link rel="stylesheet" type="text/css" href="iOSstyle.css" />;
}
else if ($detect->isMobile()) {
echo <link rel="stylesheet" type="text/css" href="mobile.css" />;
}
else{
echo <link rel="stylesheet" type="text/css" href="normal.css" />;
}
FYI, these libraries are dependent on the User-Agent value in the header and other headers too.

- 15,485
- 3
- 35
- 61
-
I tried using it to replace my current stylesheet link (before moving on to developing the mobile site, just to be safe); I get a PHP syntax error at ` – Jules Jun 29 '12 at 04:21
-
sorry my daily dealing with asp.net just overpowers other language syntax. – Baz1nga Jun 29 '12 at 04:52
Try this (if-condition written in pseudocode because I haven't used WURLF):
<?php
if (device is mobile) {
echo "<link rel='stylesheet' type='text/css' href='mobile.css' />";
}else{
echo "<link rel='stylesheet' type='text/css' href='monitor.css' />";
?>
Put this code where you'd normally have the CSS link.

- 3,723
- 4
- 15
- 19
What I've done before is store the current state (mobile/desktop) in a session variable. Then you can have a "View Desktop/Mobile Version" link which would toggle the session variable. When you render each page, use an if statement on the session variable to determine which stylesheet to display. I recommend you separate this logic into a function for re-use so you don't have to edit 20 different pages when refactoring.
If you want to auto-detect mobile browsers, you can use WURLF or php-mobile-detect.

- 7,870
- 4
- 36
- 52