Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check user open the site in App or not

Tags:

android

php

I am using following code for checking whether the user opened the site in App or not

    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    if(stripos($ua,'android') && stripos($ua,'mobile') !== false) {
    if($_SERVER['HTTP_X_REQUESTED_WITH'] == "apppackagename") {
    echo "Opening with App";
    }
   }

But this is not working in some devices like.

GT - S7582 Android Version 4.2.2

Is there any solution for this to work in old version devices?

Thanks in advance !

like image 821
Sree KS Avatar asked Jul 13 '16 13:07

Sree KS


3 Answers

You can simply include in the top https://github.com/serbanghita/Mobile-Detect/blob/master/Mobile_Detect.php It's a lightweight library and requires to include only a single file.

for example:

 require_once('Mobile_Detect.php');
 $device = new Mobile_Detect();

 if ($device->isMobile() ) {
   if( isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
       $_SERVER['HTTP_X_REQUESTED_WITH'] == "apppackagename") {
           echo "Opening with App";
       }
 }

if you want to detect android then you can type:

$device->isAndroidOS()

It's the most reliable way to detect a mobile device ( but also no bullet proof ). There is no way for reliable mobile detection with simple User Agent Check.

If you look into the source https://raw.githubusercontent.com/serbanghita/Mobile-Detect/master/Mobile_Detect.php, you can see that GT-S7582 is supported.

like image 73
Pawel Wodzicki Avatar answered Nov 02 '22 11:11

Pawel Wodzicki


I'd recommend to use a library that has a stable set of checks for mobile/app detection. The upside of this is that you can expect the framework to support upcoming devices by simply upgrading your library instead of recoding it yourself.

For PHP there seems to be Mobile-Detect, it is open source and has active contributions: https://github.com/serbanghita/Mobile-Detect

like image 38
Thomas Raffelsieper Avatar answered Nov 02 '22 09:11

Thomas Raffelsieper


If you want hide the error you need use array_key_exists in you code like this:

$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') && stripos($ua,'mobile') !== false) {
    if(array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) {
        if($_SERVER['HTTP_X_REQUESTED_WITH'] == "apppackagename") {
            echo "Opening with App";
        }
    } else {
        echo "Sorry... I don't see a package!";
    }
}

The function array_key_exists "Checks if the given key or index exists in the array".

Maybe in the future you need hide another errors, so, you can use @ to mute error. See here.

like image 1
Jorge Olaf Avatar answered Nov 02 '22 10:11

Jorge Olaf