treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Detect mobile and redirect

  • I'm not a php programmer and would like to find a php script to detect visitors who are using mobile phones to my site, and then redirect them to a subdomain on the site optimized for small screens. Can someone point me to an easy to understand and install script to do that?

    Thanks
  • @ChristopherBurton, he may want a dedicated mobile site to prevent having to load extra content which isn't needed for a mobile version. Media queries are great, but if you want a really lightweight stripped-down version of your site for mobile then redirecting to a specifically designed page is the way to go, in my opinion. Although by using adaptive images you can combat part of this problem.

    @DocRocks, you can use PHP to detect specific user agent strings, but rather than doing that it's probably a better idea to redirect based on screen size. I don't know how to do this in PHP but with jQuery you could use something like this:


    if($(window).width() < 480){
    window.location = "mobile.yoursite.com"
    }
  • @Johnnyb - Load extra content?
  • Well yeah, by that I mean the whole page and all of it's resources still have to load even if you don't use them. You may be hiding certain elements, having to scale down or hide certain images completely, including JS libraries that you don't need for the mobile version, all of which are being loaded and slowing down the page load.

    With a dedicated mobile page/site, you can include just the elements you need, reduce image size dramatically, and only load the scripts/stylesheets you need.

    There are pros and cons to both using a separate site or using media queries, but there are cases when you'd want to use the former.
  • Okay I see what you meant. I would agree and say that it is situational.
  • Thanks Christopher and Johnnyb - the simple jQuery looks like what I am after to detect small screens. I enclosed the if statement with <?php ...> tags, put it at the top of my page and changed the url but it does not redirect. Is it just my Android phone or have I missed something? PHP is enabled on my host.
  • The code that has been posted was jQuery, which is essentially JavaScript, which is NOT php. In the head tags of your page put it in like this:

    <!-- its jquery, so first of all remember to include jQuery -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script&gt;

    <!-- Next wrap your code in tags, and execute it when the document is ready -->
    <script type="text/javascript">
    $(document).ready(function(){
    if($(window).width() < 480){
    window.location = "http://mobile.yoursite.com&quot;
    }
    });
    </script>


    Hope this helps, Dave
  • @Johnnyb I think if you created a media queried site (that was serious) and you made mobiles load everything only after that they receive the media query, you're doing it wrong. Even HTML5 boilerplate promotes loading mobile styles first and desktop computers last (since desktop computers mostly have broadband capabilities)

    For example:
    @media only screen and (min-width: 480px) {

    }

    @media only screen and (min-width: 768px) {

    }

    The only problem you'll run into is lte IE 8 not supporting the media queries, however the latest modernizr has respond.js built in which solves this problem.

    So if you build the site correctly, mobiles don't have to load up any unnecessary information (aside from the size of the CSS file itself).

    @DocRocks if media queries definitely aren't for you, check out php mobile detect. I've used it before and it was great.
  • @jamy_za, I understand what you're saying but I have to disagree. Structuring the CSS like that still doesn't prevent the full HTML page and all of it's resources from being loaded. Any "desktop-sized" images and all of your HTML will still be loaded despite not being needed, along with any JS which you may not need.
    Say you want to hide a sidebar with 6 ads in it for the mobile version, if using media-queries then that sidebar and those ads are still loaded in the page, they are just hidden using display: none. If each of those ads is 10k then that's 60k (+ the weight of the HTML) which isn't needed.
  • @Johnnyb ok I see what you mean to a degree. Personally I would use the php mobile detect script above for excluding/including something like that.
  • Thanks folks. I am trying Dave's js and my Android mobile is reporting download unsuccessful for this site. The index.htm in the site root folder has Dave's code in the head area and I have pointed window.location to the index.htm file in the /mobile folder on the site. I can open the mobile site on my desktop using the full url including the index.htm in the /mobile folder. Why does my Android browser fail?
  • Sorry, having trouble with opening the site and am working with the host to resolve. Try the link to it later if necessary to help me resolve my mobile problem.
  • Site back online.
  • hey @DocRock, that redirect works on my desktop, not sure why it's not working on your android. Try using 'window.location.href' instead of just 'window.location'
  • So I have a question about this type of script. With using this jQuery method, say you want a "desktop site" type link on your mobile website (like Google has). Well, I have tested on my phone and when I access the "desktop site" link on my mobile site, it correctly redirects me to the desktop site with a href link. However, when testing with a browser on a pc, (minimizing the browser to < 480px) when I access the "desktop site" link, it begins to load the desktop site, but then redirects to the mobile site because of the browser size. Which this is correct in my understanding. But how can I get it to still view the desktop site even if below 480px, (of course only when asked to view the full desktop site)? Seems like it may take some php script dealing with cache or something?

    Thanks in advance.
  • Right - when I decrease my IE8 desktop browser to this - if($(window).width() < 480) - then redirects to the mobile page. However, this does not work on my Android smartphone - I still get the desktop version. I haven't made any changes to Dave's code other than entering the proper url. Is this just an Android problem?
  • Hey @DocRocks, have you tried changing the code to 'window.location.href' yet?

    @standuncan, you could just set a cookie when you click on the 'desktop site' link, then check against it in the JS. If width is less than 480 and desktopCookie is false then redirect to mobile site, otherwise don't.
  • Yes. Here is the code - do I have the right syntax?
    <script type="text/javascript"> $(document).ready(function(){ if($(window).width() < 480){ window.location.href = "http://alsautomotiveandtruck.com/mobile/index.htm&quot; } }); </script>
  • After viewing your source I realized that you're missing this from the top of your document:

    <meta name="viewport" content="width=device-width,initial-scale=1">

    Add that at the top of your and it'll work. The problem was that without resizing the viewport to the width of the mobile device then the window width isn't less than 480. Thus the redirect wasn't triggered.

    John
  • Hey Johnnyb. Thanks very much for hanging there with me. After adding the code to the indexTest.htm file it works in my desktop but doesn't work on my Android. I tried it first at the top of the head area, just before and after the script - same result. I tried rebooting my phone to see if there is a cache problem - nada. The script detects a narrow desktop browser - what could be the problem?
  • Hey, no worries. Try this link on your android and let me know if it works: http://johndoesdesign.com/dev/j/redirect/ I've tested it on my iphone and it works on there.

    If it works then it should redirect to http://alsautomotiveandtruck.com/mobile/
  • I get a text window that says - this should redirect to .... Doesn't redirect to my mobile site. It does redirect from my desktop IE8. What is so different about Android I wonder? BTW if you want to look at the code in the test page, the file on the site is http://alsautomotiveandtruck.com/ indexTest.htm.
  • Just tried it on an Android (Google HTC) and it works in portrait but not landscape, must be the landscape resolution which is throwing it off. I changed the query to 600px and tested on both portrait and landscape and it now works on both: http://johndoesdesign.com/dev/j/redirect/ Test it again on your phone and let me know.

    Cheers, John
  • Outstanding! That Worked! Again, thanks for all your effort to help me resolve this.
  • Hey no problem, glad we managed to get that resolved!
  • please provide the complete code and make the code redirect just mobile browsers not desktop browsers.
  • @thebliz,

    I would say that you have two options.

    1.) http://jsfiddle.net/SCm8E/1/ (which includes just the code)

    or

    2.) Read the above conversation.
  • Hi, Could anyone help please. I've tried your suggestions and cant seem to get a re direct. This is the source code I've tried. any help appreciated. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> $(document).ready(function(){ if($(window).width() < 600){ window.location.href = "http://halfmoonhousetopsham.co.uk/halfmoon_mobile.html" } });

    Untitled Document

  • That's not going to work unless you link to jQuery first.

  • MobRedirect - Mobile Detection and Redirection is one of the great script i ever found on internet...... below is script download link

    http://codecanyon.net/item/mobredirect-mobile-detection-and-redirection/3630502

  • Hi! just wanted to thank this conversation as I have rad it thru and implemented all steps successfully (thanks to Johnnyb). Now my main website diverts to mobile pages when opened on a phone. However, it just occurred to me, that I have in my mobile home page an option to go back to Classic view. That will never be achieved, as Classic view automatically diverts back to mobile. Is there any script that implements re-direction once only? Thanks in advance !! Ella

  • Hello,

    If you ever decide to use server-side mobile detection (phones or tablets), I'll point you to http://mobiledetect.net (someone else pointed to this script above, but it was the old Google Code repository). It's MIT licensed and updated weekly. I'm one of the maintainers. Just look at the examples, it's simple. Since everyone asks for both both "detection" and "redirect" or ways to choose and remember the website layout, I'll suggest using the example: https://github.com/serbanghita/Mobile-Detect/blob/devel/examples/example1.php , it's a simple procedural example, also includes an example of footer links for the visitor to choose the type of layout.

    Hope this helps.

  • Say you want to hide a sidebar with 6 ads in it for the mobile version, if using media-queries then that sidebar and those ads are still loaded in the page, they are just hidden using display: none. If each of those ads is 10k then that's 60k (+ the weight of the HTML) which isn't needed.

    https://github.com/Podders/Jquery-Media-Comments

  • I've gotten a bit confused. I have a similar problem. I built a site for someone, pretablets and smart phones. I'd have to re-build the whole site to use css media queries, I'd have to build a new responsive site. I built a totally separate jQuery mobile site, not a variation on original theme. I need a way to redirect small screens to this site, all new html and css etc., when the user device is a smart phone. Can anyone please help. I use jQuery regularly and have a basic knowledge of php. Much thanks in advance.

  • Hahaha @JohnMotylJr ! I'm lazy to ;)

  • @Johnnyb I have a question regarding the redirect: http://johndoesdesign.com/dev/j/redirect/

    How can I manage to redirect a mobile user if clicked on a link "go to desktop version" to be directed to a desktop version? Currently with your script the device still detects that the user is using mobile and redirects again to the mobile version, but loads it funnily.

    Would appreciate your assistance ;-)

  • 
    if((navigator.userAgent.match(/iPhone/i))||(navigator.userAgent.match(/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|vodafone|o2|pocket|kindle|mobile|pda|psp|treo)/i))||
    (navigator.userAgent.match(/iPod/i))||
    (navigator.userAgent.match(/operamini/i))||
    (navigator.userAgent.match(/blackberry/i))||
    (navigator.userAgent.match(/(palmos|palm|hiptop|avantgo|plucker|xiino|blazer|elaine)/i))||
    (navigator.userAgent.match(/(windowsce; ppc;|windows ce; smartphone;|windows ce;iemobile)/i))||
    (navigator.userAgent.match(/android/i)))
    {if(document.URL.indexOf('desktopsite=true')<0){window.location="<a href="http://mobile.yoursite.com" target="_blank" rel="nofollow">http://mobile.yoursite.com"}}