Identifying activity on a handheld device

I am currently working on a website and I have noticed that it doesn't work as well on mobile devices as it does on desktop. There are performance issues that need to be addressed. I've seen other websites redirecting users to a different page when accessing the site from a mobile device, and I would like to implement something similar with a message pop-up instead. While I am confident in my ability to create the message, I need help with the process of detecting mobile device usage. I found a website that could potentially help, but I'm unsure how to integrate it using JS.

If anyone can provide assistance with this, I would greatly appreciate it!

Answer №1

Give this a shot

/**
    * Device Detector
    * @license    http://www.opensource.org/licenses/mit-license.php The MIT License
*/
class Device_Detector
{
    protected $accept;
    protected $userAgent;
    protected $isDevice = false;
    protected $isAndroid = null;
    protected $isAndroidtablet = null;
    protected $isIphone = null;
    protected $isIpad = null;
    protected $isBlackberry = null;
    protected $isBlackberrytablet = null;
    protected $isOpera = null;
    protected $isPalm = null;
    protected $isWindows = null;
    protected $isWindowsphone = null;
    protected $isGeneric = null;
    protected $devices = array(
    "android" => "android.*mobile",
    "androidtablet" => "android(?!.*mobile)",
    "blackberry" => "blackberry",
    "blackberrytablet" => "rim tablet os",
    "iphone" => "(iphone|ipod)",
    "ipad" => "(ipad)",
    "palm" => "(avantgo|blazer|elaine|hiptop|palm|plucker|xiino)",
    "windows" => "windows ce; (iemobile|ppc|smartphone)",
    "windowsphone" => "windows phone os",
    "generic" => "(kindle|mobile|mmp|midp|pocket|psp|symbian|smartphone|treo|up.browser|up.link|vodafone|wap|opera mini)");

    public function __construct()
    {
        $this->userAgent = $_SERVER['HTTP_USER_AGENT'];
        $this->accept = $_SERVER['HTTP_ACCEPT'];

        if (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE']))
        {
            $this->isDevice = true;
        }
        elseif (strpos($this->accept, 'text/vnd.wap.wml') > 0 || strpos($this->accept, 'application/vnd.wap.xhtml+xml') > 0)
        {
            $this->isDevice = true;
        }
        else
        {
            foreach ($this->devices as $device => $regexp)
            {
                if ($this->checkForDevice($device))
                {
                    $this->isDevice = true;
                }
            }
        }
    }

    /**
        * Overloads isAndroid() | isAndroidtablet() | isIphone() | isIpad() | isBlackberry() | isBlackberrytablet() | isPalm() | isWindowsphone() | isWindows() | isGeneric() through checkForDevice()
        *
        * @param string $name
        * @param array $arguments
        * @return bool
    */
    public function __call($name, $arguments)
    {
        $device = substr($name, 2);
        if ($name == "is" . ucfirst($device) && array_key_exists(strtolower($device), $this->devices))
        {
            return $this->checkForDevice($device);
        } 
        else
        {
            trigger_error("Method $name not defined", E_USER_WARNING);
        }
    }

    /**
        * Returns true if any type of device detected, including special ones
        * @return bool
    */
    public function isDevice()
    {
        return $this->isDevice;
    }

    protected function checkForDevice($device)
    {
        $var = "is" . ucfirst($device);
        $result = $this->$var === null ? (bool) preg_match("/" . $this->devices[strtolower($device)] . "/i", $this->userAgent) : $this->$var;
        if ($device != 'generic' && $result == true) {
            $this->isGeneric = false;
        }
        return $result;
    }
}   

   //utilize the class like so
    $detector= new Device_Detector();
    if ($detector->isDevice())
    {
        $_SESSION['device']="device";
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending information from Ajax to PHP

Could anyone please explain the script provided above to me? I am attempting to pass the value of $user data so that I can utilize $_REQUEST['user'] within sort.php, but I am encountering difficulties. It seems to be passing in a long URL. $(fun ...

I've been attempting to develop a React application, but I consistently encounter the following error: "npm ERR! cb() function was never invoked!"

Here is the issue at hand: HP@DESKTOP-1HP83V8 MINGW64 ~/Desktop/Web-Development (master) $ npx create-react-app my-app A new React app is being created in C:\Users\HP\Desktop\Web-Development\my-app. Packages are being installed. ...

Streamlining programming by utilizing localStorage

Is there a more efficient way to streamline this process without hard-coding the entire structure? While attempting to store user inputs into localStorage with a for loop in my JavaScript, I encountered an error message: CreateEvent.js:72 Uncaught TypeErr ...

Form Input Field with Real-Time JavaScript Validation

Is there a way to validate the content of a textarea using pure JavaScript, without using jQuery? I need assistance with this issue. <script> function validate() { // 1. Only allow alphanumeric characters, dash(-), comma(,) and no spaces ...

Positioning the comments box on Facebook platform allows users to

Need assistance, I recently integrated the Facebook comments box into my Arabic website, but I am facing an issue where the position of the box keeps moving to the left. Here is an example of my website: Could someone please suggest a solution to fix the ...

Troubleshooting compatibility issues between Sailsjs Services and TypeScript in Vscode

Having an issue with TypeScript in a Sails.js application. I am utilizing TypeScript to write my controller and attempting to use Sails.js services within the controllers. However, I encounter a syntax error in VSCODE. Below is the code snippet from MyCo ...

Steps for adjusting the status of an interface key to required or optional in a dynamic manner

Imagine a scenario where there is a predefined type: interface Test { foo: number; bar?: { name: string; }; } const obj: Test; // The property 'bar' in the object 'obj' is currently optional Now consider a situatio ...

Guide on adjusting PHP variable values and updating functions with ajax requests

One of my functions determines dates based on a variable For example: $modification = "+1 Week" function updateCalendar($change){ $month = array("January","February","March","April","May","June","July","August","September","October","November","Dece ...

Align an element to the center and then align a second element to the right using Tailwind CSS

Here is a visual representation of my goal: the dashed line indicates the center of the container. My objective is to horizontally center one div element and then right-align a second div within the same row, all while keeping both elements centered. htt ...

Display data from a PHP array in a JavaScript alert box

Within my Wordpress registration form, I am attempting to display the $error array in an alert message. I have experimented with using console.log(), but it does not show any output. Even when using JSON.stringify(), the alert only displays the word: true ...

One helpful tip for adjusting the size of a UI chip on the fly

I am attempting to adjust the size of a UI chip dynamically based on the font size of its parent elements using the em unit in CSS. My objective is to achieve something like this: style={{size:'1em'}} The issue I'm encountering: The chip e ...

NuxtJS - Google Auth: ExpiredAuthSessionError: The authentication session has expired because both the token and refresh token have expired. Please try your request

I've been using nuxtjs for some time now. Everything related to authentication was working smoothly until my last update. However, after updating the nuxt.config.js file and moving the axios plugin from the plugins array to the auth config object, an ...

What could be causing the failure of the update for this computed property in my Vue 3 application?

Currently, I am in the process of creating an audio player using Vue 3 and the Napster API. About the Project I have managed to make the vinyl rotate by utilizing a CSS keyframes-based animation paired with the computed property isSpinning. I intend for ...

I'm attempting to retrieve information from my vuex store, however, encountering an error in the process

I've encountered an issue with vuex getters while working on my project. I have a route that showcases all users, and upon visiting this route, the AllUsers.vue component is displayed. Within this component, I'm utilizing the UsersList.vue compo ...

The use of set.has in filtering does not produce the desired outcome

I am attempting to use Set.has to filter an array in the following way: const input = [ { nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' }, { nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' }, { ...

Guide to Inputting Numbers in a Form Field using a Pop-up Keypad (with Javascript/AJAX)

I am working on a small project that involves creating a keypad with buttons for all the digits, backspace, and decimal. When these buttons are clicked, they should populate a form field like a text box. The keypad will be located next to the form field as ...

Parent container fails to center align when window is resized

When I resize my window to a smaller size, like that of a smartphone screen, the three inner divs (colored red, green, and blue - .left, .center, and .right) do not align in the center. Please refer to the screenshot attached for clarity. My goal is to ens ...

When clicked, the onClick feature will reduce the number each time instead of initiating the timer

Currently, I am working on a meditation application using React. As a starting point, I implemented a 25-minute countdown feature. The challenge I am facing is that the timer starts counting down each time the button is clicked, rather than triggering it ...

Creating a basic bar graph using d3.js with an array of input data

In my dataset, I have an array of form data that includes items like 'Male', 'Female', 'Prefer Not To Say'. I want to create a simple bar chart generator using D3.js that can display the percentages or counts of each item in t ...

"Encountering an issue with AJAX file upload displaying an error message for

Before I showcase my code, allow me to explain my objective. My goal is to create a page that updates a user's details in the database using AJAX. Initially, I successfully achieved this task. Subsequently, I wanted to enhance the functionality by inc ...