News Ticker

Using PHP or Javascript-How to redirect mobile users to mobile version website

By Unknown - Friday, 13 November 2015 No Comments
hello friends, i was working on About Me webpage, which is optimised for desktop browsers.
i had developed a mobile browser page for About Me, now the problem was how to detect mobile users and redirect them to mobile version of webpage.
i solved this problem, and found interesting to share with you.
this problem can be solved in two way:
1. using codes on server side (PHP):
Add below code to your index file (.php) or header.php (if using wordpress), it will detect user agent (device type) and redirect to mobile url (http://mobileversion.com).

<?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)
{ echo "<script>window.location='http://mobileversion.com'</script>"; }
?>

2. using codes on client side (JavaScript):
There are two ways, A. By Detecting User Agent by using below code:

<script>
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){
if(document.URL !="http://mobileversion.com")
{ window.location ="http://mobileversion.com"; }
}
</script>

And B. By using screen width by implementing below code:
<script type="text/javascript">
if (screen.width <= 800) { window.location = "http://mobileversion.com"; }
</script>


Similarly if you want to redirect mobile to desktop just reverse all if condition ;)

No Comment to " Using PHP or Javascript-How to redirect mobile users to mobile version website "