Home » Php » php – Check user open the site in App or not

php – Check user open the site in App or not

Posted by: admin July 12, 2020 Leave a comment

Questions:

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 !

How to&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.

Answer:

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

Answer:

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_existsChecks 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.