Redirect Mobile Devices with PHP
Wall Script
Follow Me:
Wednesday, September 22, 2010

Redirect Mobile Devices with PHP

Are you looking for mobile website redirection script. Take a look at this post I want to explain how to detect mobile user agents like Android, Iphone and Blackberry. Many people are suggested to redirect with .htaccess file but I had implemented this with PHP. It is very easy just few lines of code.

Redirect mobile devices


Demo: Try to open labs.9lessons.info with mobile devices it will be redirect to touch.9lessons.info (mobile site)

$_SERVER - Server and execution environment information (More info)
<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>

My Android browser Output:

Mozilla/5.0 (Linux; U; Android 2.1-update1; en-in; HTC_Wildfire_A3333 Build/ERE27) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari


user_agent.php
Usining strpos() function find position of first occurrence of a string. (more details)
<?php
$iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
$palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
$berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
$ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

if ($iphone || $android || $palmpre || $ipod || $berry == true)
{
header('Location: http://mobile.site.com/');
//OR
echo "<script>window.location='http://mobile.site.com'</script>";
}
?>

Index.php or Home.php
You have to include like following script.
<?php
include('user_agent.php'); // Redirecting http://mobile.site.info
// site.com data
?>

Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


92 comments:

  1. Useful info.. a bit simple in php

    ReplyDelete
  2. Veri good and sencile, i saw another but this is better... Cong...Srinvas!!!

    ReplyDelete
  3. nice...
    can anybody find a standard mobile redirect..

    example:
    using laptop/pc -> twitter.com
    if user using mobile device -> m.twitter.com

    ReplyDelete
  4. Very useful and simple script thx....

    ReplyDelete
  5. Good, simple... I like it>
    But I don't understand something "if ($iphone || $android || $palmpre || $ipod || berry == true)"

    The test for the BlackBerry..
    1. Why need to "== true"
    2. No need for "$" before "berry"

    maybe two stupids questions, but if you can explain, it?
    Thank you

    ReplyDelete
  6. @Pierre

    It was my mistake now modified ..

    ReplyDelete
  7. preg_match would be faster me thinks...

    $phones = array('iPhone', 'Android', 'BlackBerry');

    if ( preg_match('/('.implode('|', $phones).')/i', $_SERVER['HTTP_USER_AGENT']) ){
    redirect
    }

    It is also more readable imo.

    ReplyDelete
  8. Good this is so useful for me because I want to implement like this code.

    ReplyDelete
  9. You can also use the Wurfl service. A bit more complete.

    http://labs.thesedays.com/2010/07/29/an-easy-way-to-detect-mobile-devices/

    ReplyDelete
  10. How About Nokia, Sony Ericcson, Samsung, Philips ??
    Please Share....

    ReplyDelete
  11. @owd

    Here's a good list for you.
    http://www.zytrax.com/tech/web/mobile_ids.html

    ReplyDelete
  12. If you're using cPanel, it might be best to create a separate control panel and add an A record for mobile, depending on how much traffic you're getting (mobile.yourdomain.com has its own cPanel, separate from yourdomain.com). That way you cut down on process limits defined by your webhost. It can also serve as a security feature in case your site is ever hacked, as /home/mainsite/ is separate from /home/mobsite/.

    ReplyDelete
  13. #!/usr/bin/perl
    2 require 'includes/config.inc.pl';
    3 require 'includes/functions.inc.pl';
    4
    5 use CGI;
    6 $query = new CGI;
    7
    8 $useragent = $ENV{HTTP_USER_AGENT};
    9 $sitepref = $query->cookie( 'SITEPREF' );
    10
    11 if ( ismobile( $useragent ) ) {
    12 if ( !$sitepref ) {
    13 if ( isipad( $useragent ) ) {
    14 print $query->redirect( "$IPADURL" );
    15 } else {
    16 if ( isiphone( $useragent ) ) {
    17 print $query->redirect( "$IPHONEURL" );
    18 } else {
    19 print $query->redirect( "$MOBILEURL" );
    20 }
    21 }
    22 } else {
    23 if ( $sitepref=='MOBILE' ) {
    24 print $query->redirect( "$MOBILEURL" );
    25 } else {
    26 if ( $sitepref=='IPHONE' ) {
    27 print $query->redirect( "$IPHONEURL" );
    28 } else {
    29 if ( $sitepref=='IPAD' ) {
    30 print $query->redirect( "$IPADURL" );
    31 } else {
    32 print $query->redirect( "$NORMALURL" );
    33 }
    34 }
    35 }
    36 }
    37 } else {
    38 if ( !$sitepref ) {
    39 print $query->redirect( "$NORMALURL" );
    40 } else {
    41 if ( $sitepref=='MOBILE' ) {
    42 print $query->redirect( "$MOBILEURL" );
    43 } else {
    44 if ( $sitepref=='IPAD' ) {
    45 print $query->redirect( "$IPADURL" );
    46 } else {
    47 if ( $sitepref=='IPHONE' ) {
    48 print $query->redirect( "$IPHONEURL" );
    49 } else {
    50 print $query->redirect( "$NORMALURL" );
    51 }
    52 }
    53 }
    54 }
    55 }

    ReplyDelete
  14. Superb discussion thank you for sharing.

    ReplyDelete
  15. Where should I put each part of the code? I'm noob in php

    ReplyDelete
  16. Well, the post is really the freshest on this valuable topic. I fit in with your conclusions and will thirstily look forward to your next updates.

    ReplyDelete
  17. This method works great - I use it for www.digisolved.com and it works great!

    ReplyDelete
  18. For some reason I'm getting a T_VARIABLE parse error on line 8 with the code above. Is anyone else having this issue?

    ReplyDelete
  19. Further to my last comment, the only way I could find to stop the issue was to remove $berry from the if/else statement. It still caused an issue even when I tried renaming it. Very strange.

    ReplyDelete
  20. I would like to forward all mobile devices to the mobile site. But give the option to view the full site from the mobile. So how would I disable this script if they choose the full site on the mobile device?

    ReplyDelete
  21. Wow It is nice info. I like it. Thanks a lot.

    ReplyDelete
  22. I tested your demo on my blackberry and it doesn't redirect :/

    ReplyDelete
  23. Hi. Thanks, great. Using it on http://www.lane.no/

    ReplyDelete
  24. For anyone interested, I wanted a php redirect that only redirected mobile users on the home page to a mobile site but that also gave them the option of going to the live site. To do this I created a link on the mobile site that creates a cookie and checked for the cookie in the index.php before doing the redirect.

    Code added to index.php:

    $mobile = 'http://mobile.mysite.com/';

    if ((strstr($_SERVER['HTTP_USER_AGENT'], 'iPhone')) && empty($_COOKIE["mobilesitez"]) && $_SERVER['REQUEST_URI']=="/") {
    header("Location: " . $mobile);
    }

    Code added to mobile page:

    function set_cookie () {
    document.cookie = 'mobilesitez=mobilesitez; domain=.mysite.com;';
    window.location = 'http://www.mysite.com/'
    }

    P.S. I had to remove the javascript style tags and the HTML A tag that calls it in order to post it in this comment. But you should be able to add those yourself. :)

    ReplyDelete
  25. Thanks! Most appreciated!

    ReplyDelete
  26. Thanks so much worked perfect for me...Really simple.

    ReplyDelete
  27. I see the 3 sets of code above but I am new to this and don't know where to put the code.

    Where do we put
    $_SERVER and user_agent.php and

    Index.php or Home.php

    ReplyDelete
  28. thank you very much.

    your tutorial is really easy to understand for beginners :)

    ReplyDelete
  29. HTC Desire not redirecting in demo at all so Im not gonna try this :(

    ReplyDelete
  30. Thanks dude!
    for nokia is just add this
    $symbian = strpos($_SERVER['HTTP_USER_AGENT'],"Symbian");

    and add $symbian in "if row"

    ReplyDelete
  31. Will this php scipt work if I'm not using php for the site pages? It's all xhtml.

    ReplyDelete
  32. hi,I am completely new to this stuff.i tried to access labs.9lessons.info from my android,got the page ,was not diverted to touch??

    ReplyDelete
  33. why so complicated???

    whats wrong with:
    php:
    $browser = get_browser(null, true);
    if ($browser["ismobiledevice"] == true) {
    //redirect to mobile page
    }

    ReplyDelete
  34. Great script I tried it and it worked simple as 1, 2, 3!

    ReplyDelete
  35. this is very usefull script for mobile web

    ReplyDelete
  36. Thanks everyone, I already have a script that is working fine except that it does not work on Nokia Browsers and they keep viewing the full site which i don't like. Can anyone help with with the code for just detecting Nokia Browers.

    Waiting in anticipation, thank you all.

    You guys are great

    ReplyDelete
  37. hi i want index.php (have redirect to home page, iphone page, i badpage, blackberry page and mobile default page) but i don't know to creating in php anyone for help me here please

    ReplyDelete
  38. Why not just use a bit of JS to detect a screen size smaller than 480px and redirect? that way you dont have to worry about accounting for all useragents.

    <5cript type="text/java5cript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
    <5cript type="text/java5cript">
    $(document).ready(function(){
    if($(window).width() < 480){
    window.location = "http://m.yoursite.com";
    }
    });


    - had to change the '5cript' tags to post this, so obviously, change the '5' in the '5cript' tags to an 's'

    ReplyDelete
  39. This is a great JS alternative. Thanks for putting it together for us.

    ReplyDelete
  40. i try do this one for mysite.And i success to repair mysite.

    Thanks

    ReplyDelete
  41. Love this! Seemed to be only one I found that worked. All the others that I tried gave me a PHP error that headers couldn't be modified and the page never loaded. One thing - I still get the error (with this script) on the Iphone but it does go away when the page is loaded. Any ideas? I dont need help just thoughts on what is causing this.

    ReplyDelete
  42. You don't have to actually echo $_SERVER['HTTP_USER_AGENT']; first, do you? I'm gonna try this out tomorrow, my shift is over now.

    ReplyDelete
  43. there is a problem with blackberry, this script doesn't recognise bb10.

    user agent is new, changed. any idea?

    i'm trying with:
    $berry10 = strpos($_SERVER['HTTP_USER_AGENT'],"BB10.+Mobile");

    ReplyDelete
  44. It does the job!
    Thank you very much!

    ReplyDelete
  45. this is very usefull script for mobile web

    ReplyDelete
  46. using this on my project. thank u very much, sir!

    ReplyDelete
  47. Can someone Please explain to me how to implement this code. I'm a newbie.
    I have a website in html code not php, what do I need to do? Thank you.

    ReplyDelete
  48. How i can find user request coming from mobile or pc. i create one mobile site and one pc website. if user on mobile then mobile site open and if user on pc then pc website open. my code in jsp.

    ReplyDelete
  49. what should it be for windows phone?

    ReplyDelete
  50. fantabulous bro...

    ReplyDelete
  51. Awesome.. Ive used the same for my personal website redirection(PHP solution instead of javascript). Thankyou for sharing this.

    ReplyDelete
  52. Implamentation

    create a page called "user_agent.php" and add the code in the window above to it.

    then chage your index.html page to index.php and add the code above from the "Index.php or Home.php" window.

    then link to your home page via your domain links as .php not .html

    this can effect or break any back links on the web directed at the origional .html and not .php
    so you may also want another edirect from an .html link index.

    how it works.

    the client requests your domain
    the server {PHP Sopported...} reads the redirect code on the 1st page or the regular page if its a decktop. the "include" code on this pages reads the "user_agent.php" and checks to see if its a mobil device... if it is it redirects to the header if not it continues the origional desktop version of the page.

    ReplyDelete
  53. Really Good Stuff.....Thank you so much Mr.Srinivas Tamada. You have solved my big problem...

    ReplyDelete
  54. Saved me from hours of extra work thanks!

    ReplyDelete
  55. function isMobileAgent($agent){
    //add unique mobile user agent string
    $mobile=array("Android","BlackBerry","iPhone","--add-more-list--");

    foreach($mobile as $v){
    if(strpos($agent,$v)!==false) return true;
    }
    return false;
    }

    //use script
    if(isMobileAgent($_SERVER['HTTP_USER_AGENT'])) echo "Mobile Users";
    else echo "PC Users";

    ReplyDelete
  56. Hi, thanks a million for this script! i was nearly desperate as one of my sites could be redirected because of its responsive design...
    My question is... i can't see symbian (nokia) on it. Can i add it manually and it works or wouldn't it work?
    Example:
    $nokia = strpos($_SERVER['HTTP_USER_AGENT'],"nokia");

    if ($iphone || $android || $palmpre || $ipod || $berry || $symbian == true)

    would that work?

    ReplyDelete
  57. Had some trouble by submitting my post so i dont know it came through... Here again:

    Would it also work with Symbian Phone ie: Nokia if i add it to the script?

    Example:
    $nokia = strpos($_SERVER['HTTP_USER_AGENT'],"nokia");

    if ($iphone || $android || $palmpre || $ipod || $berry || $symbian == true)
    {

    ReplyDelete
  58. How to redirect the page when search in browser like google

    ReplyDelete
  59. I quote "Try to open labs.9lessons.info with mobile devices it will be redirect to touch.9lessons.info (mobile site)"
    But when I tried it on my Samsung Galaxy Grand aneroid phone, it sent me to: labs.9lessons.info/login.php
    and not to the mobile site

    ReplyDelete
  60. How its work:

    $nokia = strpos($_SERVER['HTTP_USER_AGENT'],"nokia");

    if ($iphone || $android || $palmpre || $ipod || $berry || $symbian == true)
    {

    "Variable name :$nokia and you called variable in the If statement is
    || $symbian? Is it correct??? "

    ReplyDelete
  61. Good information :)

    ReplyDelete
  62. Thank you so much. much simple code.

    ReplyDelete
  63. nice script, very helpfull, thank you

    ReplyDelete
  64. Thanks for sharing this script!

    ReplyDelete
  65. Nice script,
    How to redirect the page on Windows Phone?

    ReplyDelete
  66. Thanks again and we look forward to hearing from you guys!

    ReplyDelete
  67. post useful things for my blog. thank's

    ReplyDelete
  68. This is simple and works super
    thanks for share information

    ReplyDelete
  69. I really think your information is a good for me to lesson many more.
    Thank you and nice tobe here.

    Regards,

    ReplyDelete
  70. Come here looking for something new and good lesson with 9lessons.info...thank you

    ReplyDelete
  71. Great posting in here...of course great people...would thank you for you for many lesson

    ReplyDelete
  72. Hhmm...i am familiar with html code in blogger than PHP, i am still confiuse...

    ReplyDelete
  73. after I took time to read from an article that you share. I was able to reap the benefits of what is contained in the content of this material

    ReplyDelete
  74. This information has long'm looking for. Finally I found it on your website. Thank you. Another time I will travel back to your website.

    ReplyDelete
  75. I like the articles you post

    ReplyDelete
  76. I'm really excited to be here with your thinking make this post awesome

    ReplyDelete

Make in India