Do you want to be a good Web Developer?

Enter Your Email To Get Our Exclusive Tutorials
And Offer Right In Your Email

Join TalkersCode Community And Recieve Exclusive Tutorials
On Web Development Right Via Email.

Detect And Redirect To Mobile Site Using PHP

Wednesday, Jan 11, 2017

Tags:- PHP


Mobile Site is one of the huge transformation we had seen in web due to the increasing number of mobile devices and of different sizes it becomes difficult to show appropriate version of website to the user. So,In this tutorial we will show you how to detect and redirect to a mobile site using PHP.There is a PHP class used for detecting mobile devices Mobile Detect we use this class to detect the mobile devices.You may also like redirect webpage after delay.


Detect And Redirect To Mobile Site Using PHP


To Detect And Redirect To Mobile Site It Takes Only Two Steps:-

  1. Make a PHP file and define markup for sample webpage
  2. Make a PHP file and define code to detect and redirect


Step 1.Make a PHP file and define markup for sample webpage

We make a PHP file and save it with a name detect_redirect.php

<?php
require_once 'redirect.php';
?>

<html>
<body>
<div id="wrapper">
 <h1>Detect And Redirect To Mobile Site Using PHP</h1>
</div>
</body>
</html>

In this step we create a sample page and add redirect.php page which is the main page used to detect and redirect to mobile site.You may also like detect adblocker using JavaScript.



Step 2.Make a PHP file and define code to detect and redirect

We make a PHP file and save it with a name redirect.php

<?php
$detect_device = new Mobile_Detect;

// For All Mobile Devices
if($detect_device->isMobile()) 
{
 header('Location: http://m.samplesite.com/');
 exit;
}

// For All Tablet Devices
if( $detect_device->isTablet()) 
{
 header('Location: http://m.samplesite.com/');
 exit;
}

// For Specific Operating System
if( $detect_device->isAndroidOS()) 
{
 echo "<link rel='stylesheet' href='android.css type='text/css' />";  
}
if( $detect_device->isiOS()) 
{
 echo "<link rel='stylesheet' href='ios.css type='text/css' />"; 
}
if( $detect_device->isWindowsPhoneOS()) 
{
 echo "<link rel='stylesheet' href='windows.css type='text/css' />";  
}

In this step there are two ways to detect you can use global method which is isMobile and isTablet to detect mobile and tablet devices and redirect to mobile site or you can also use specific styling for specific operating system like isAndroidOS is used to detect whether the user operating system is android or not if yes it use different css for android devices same as for ios and windows.You may also like detect url in input using jQuery.


Thats all, this is how to detect and redirect to mobile site using PHP.You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

Join Us With Our 21000+ Subscribers And Get Our Latest Tutorials Update Via Email