August 12, 2014 6:53 pm

How to detect device and redirect to mobile website in PHP

As we all know that most of the peoples use mobiles and tablets instead of using computer all the day and as a web developer / designer you need to create your websites Compatible to all devices with responsive designs or you can simply create different sites for mobile and tablet users on a subdomain with compatibility. Today I am going to show you that How to detect device and redirect user on compatible site.

How to detect device and redirect to mobile website in PHP

[wpdm_file id=109]DEMO

We have used a PHP class Mobile-Detect it uses the User-Agent string combined with specific HTTP headers to detect the mobile environment. You can get this class from github or download our demo which also contain that class and live demo files.

PHP Code:

index.php Contains php code to detect device and redirect if device is mobile or tablet.

<?php
require_once 'Mobile_Detect.php'; // PHP Class to detect device.
$objMobile = new Mobile_Detect;
 
if($objMobile ->isMobile()) {
    header('Location: http://m.yoursite.com/');
    exit;
}
?>

Above code will redirect user to website’s mobile version if user coming from a mobile device.

Some other cases to redirect website:

<?php
if( $detect->isTablet()) {
   // Redirect or operate any tablet device.
}
 
if( $detect->isMobile() && !$detect->isTablet()) {
    // Exclude tablets devices and used for mobile only.
}

if( $detect->isAndroidOS()) {
    // Check for Android platforms
}
 
if( $detect->isiOS()) {
   // Check for iOS platforms
}
 
if( $detect->isWindowsPhoneOS()) {
   // Check for Windows Phone platforms
}
// many more like browser's etc you can filter
?>

Above code shows you more specific checks for device you user using so I hope this tutorial helps you and please dont forget to share it with your friends and do comment you issues and suggestion for our upcoming articles.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

10 responses to “How to detect device and redirect to mobile website in PHP”

  1. Ravi Agarwal says:

    Its cool and awesome u are great man

  2. Ruslan says:

    already using half a year

  3. maxx says:

    It is really old idea, better do responsive website to support all device

  4. Dubba Ramesh says:

    nice article..

  5. Very useful, Thank you very much.

  6. Chandrakant Patel says:

    how to detect device using API from native application of mobile

Leave a Reply

Your email address will not be published. Required fields are marked *