Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to redirect single php page for mobile devices with PHP/Javascript

Tags:

javascript

php

I have a PHP google map application that I want to make visible to users when they are using a desktop but redirect to another PHP page if the visitor is using a mobile device. I know there are numerous ways to do this from OS to browser type detection but was wondering if someone could provide some code they feel is the best way to handle this and it being the most consistent?

like image 597
Rocco The Taco Avatar asked Oct 28 '12 14:10

Rocco The Taco


People also ask

How do I redirect from one PHP to another?

Answer: Use the PHP header() Function You can simply use the PHP header() function to redirect a user to a different page. The PHP code in the following example will redirect the user from the page in which it is placed to the URL http://www.example.com/another-page.php . You can also specify relative URLs.

How many ways I can redirect a PHP page?

Redirection from one page to another in PHP is commonly achieved using the following two ways: Using Header Function in PHP: The header() function is an inbuilt function in PHP which is used to send the raw HTTP (Hyper Text Transfer Protocol) header to the client.

Which PHP code is used to redirect into page Mypage HTML?

To redirect the visitor to another page (particularly useful in a conditional loop), simply use the following code: <? php header('Location: mypage.

Which function in PHP is used to redirect from one page to another page?

The header function in PHP can be used to redirect the user from one page to another. It is an in-built function that sends raw HTTP header to the destination (client).


2 Answers

If you don't want to use javascript, you can handle it via php. Take a look at this lib: http://code.google.com/p/php-mobile-detect/. And then you could do something like:

<?php
include 'Mobile_Detect.php';
$detect = new Mobile_Detect();

if ($detect->isMobile()) {
    header('Location: yourpage.php');
    exit(0);
}
like image 136
jacoz Avatar answered Sep 29 '22 00:09

jacoz


Disclaimer: I know this regex is not perfect, so don't down vote just for that :)

Just wanted to share these few points.

  1. Some servers have $_SERVER['HTTP_USER_AGENT'] as not set, so make sure to check if empty first
  2. Readability is important to us, so we are using this instead of others complex regex. Just add other devices as you see fit.

Here is the code we use:

<?php
if(! empty($_SERVER['HTTP_USER_AGENT'])){
    $useragent = $_SERVER['HTTP_USER_AGENT'];
    if( preg_match('@(iPad|iPod|iPhone|Android|BlackBerry|SymbianOS|SCH-M\d+|Opera Mini|Windows CE|Nokia|SonyEricsson|webOS|PalmOS)@', $useragent) ){
        header('Location: ./mobile/');
    }
}
?>
like image 29
fedmich Avatar answered Sep 29 '22 01:09

fedmich